blob: 474db47c236bccc9f4d62dd839a193c178856f32 [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 Wangb254fa32017-01-31 17:43:23 -0800351 if (mStartBootAnimThread->join() != NO_ERROR) {
352 ALOGE("Join StartBootAnimThread failed!");
353 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800354 const nsecs_t now = systemTime();
355 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000356 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700357 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700358
359 // wait patiently for the window manager death
360 const String16 name("window");
361 sp<IBinder> window(defaultServiceManager()->getService(name));
362 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700363 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700364 }
365
Steven Thomas050b2c82017-03-06 11:45:16 -0800366 if (mVrFlinger) {
367 mVrFlinger->OnBootFinished();
368 }
369
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700370 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700371 // formerly we would just kill the process, but we now ask it to exit so it
372 // can choose where to stop the animation.
373 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700374
375 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
376 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
377 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700378
379 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
380 readPersistentProperties();
381 });
382 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800383}
384
Mathias Agopian3f844832013-08-07 21:24:32 -0700385void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700386 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700387 RenderEngine& engine;
388 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700389 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700390 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
391 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700392 }
393 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700394 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700395 return true;
396 }
397 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700398 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700399}
400
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700401class DispSyncSource : public VSyncSource, private DispSync::Callback {
402public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700403 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000404 const char* name) :
405 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700406 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700407 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000408 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
409 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700410 mDispSync(dispSync),
411 mCallbackMutex(),
412 mCallback(),
413 mVsyncMutex(),
414 mPhaseOffset(phaseOffset),
415 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700416
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700417 virtual ~DispSyncSource() {}
418
419 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700420 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700421 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000422 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700423 static_cast<DispSync::Callback*>(this));
424 if (err != NO_ERROR) {
425 ALOGE("error registering vsync callback: %s (%d)",
426 strerror(-err), err);
427 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700428 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700429 } else {
430 status_t err = mDispSync->removeEventListener(
431 static_cast<DispSync::Callback*>(this));
432 if (err != NO_ERROR) {
433 ALOGE("error unregistering vsync callback: %s (%d)",
434 strerror(-err), err);
435 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700436 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700437 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700438 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700439 }
440
441 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700442 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700443 mCallback = callback;
444 }
445
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700446 virtual void setPhaseOffset(nsecs_t phaseOffset) {
447 Mutex::Autolock lock(mVsyncMutex);
448
449 // Normalize phaseOffset to [0, period)
450 auto period = mDispSync->getPeriod();
451 phaseOffset %= period;
452 if (phaseOffset < 0) {
453 // If we're here, then phaseOffset is in (-period, 0). After this
454 // operation, it will be in (0, period)
455 phaseOffset += period;
456 }
457 mPhaseOffset = phaseOffset;
458
459 // If we're not enabled, we don't need to mess with the listeners
460 if (!mEnabled) {
461 return;
462 }
463
464 // Remove the listener with the old offset
465 status_t err = mDispSync->removeEventListener(
466 static_cast<DispSync::Callback*>(this));
467 if (err != NO_ERROR) {
468 ALOGE("error unregistering vsync callback: %s (%d)",
469 strerror(-err), err);
470 }
471
472 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000473 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700474 static_cast<DispSync::Callback*>(this));
475 if (err != NO_ERROR) {
476 ALOGE("error registering vsync callback: %s (%d)",
477 strerror(-err), err);
478 }
479 }
480
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700481private:
482 virtual void onDispSyncEvent(nsecs_t when) {
483 sp<VSyncSource::Callback> callback;
484 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700485 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700486 callback = mCallback;
487
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700488 if (mTraceVsync) {
489 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700490 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700491 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700492 }
493
494 if (callback != NULL) {
495 callback->onVSyncEvent(when);
496 }
497 }
498
Tim Murray4a4e4a22016-04-19 16:29:23 +0000499 const char* const mName;
500
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700501 int mValue;
502
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700503 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700504 const String8 mVsyncOnLabel;
505 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700506
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700507 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700508
509 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700510 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700511
512 Mutex mVsyncMutex; // Protects the following
513 nsecs_t mPhaseOffset;
514 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700515};
516
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700517class InjectVSyncSource : public VSyncSource {
518public:
519 InjectVSyncSource() {}
520
521 virtual ~InjectVSyncSource() {}
522
523 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
524 std::lock_guard<std::mutex> lock(mCallbackMutex);
525 mCallback = callback;
526 }
527
528 virtual void onInjectSyncEvent(nsecs_t when) {
529 std::lock_guard<std::mutex> lock(mCallbackMutex);
530 mCallback->onVSyncEvent(when);
531 }
532
533 virtual void setVSyncEnabled(bool) {}
534 virtual void setPhaseOffset(nsecs_t) {}
535
536private:
537 std::mutex mCallbackMutex; // Protects the following
538 sp<VSyncSource::Callback> mCallback;
539};
540
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700541void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700542 ALOGI( "SurfaceFlinger's main thread ready to run. "
543 "Initializing graphics H/W...");
544
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900545 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
546
Dan Stoza9e56aa02015-11-02 13:00:03 -0800547 { // Autolock scope
548 Mutex::Autolock _l(mStateLock);
549
550 // initialize EGL for the default display
551 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
552 eglInitialize(mEGLDisplay, NULL, NULL);
553
554 // start the EventThread
555 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
556 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700557 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800558 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
559 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700560 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800561 mEventQueue.setEventThread(mSFEventThread);
562
Tim Murray22752852017-05-04 13:38:49 -0700563 // set EventThread and SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700564 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700565 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700566 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
567 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
568 }
Tim Murray22752852017-05-04 13:38:49 -0700569 if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
570 ALOGE("Couldn't set SCHED_FIFO for EventThread");
571 }
Tim Murray41a38532016-06-22 12:42:10 -0700572
Dan Stoza9e56aa02015-11-02 13:00:03 -0800573 // Get a RenderEngine for the given display / config (can't fail)
574 mRenderEngine = RenderEngine::create(mEGLDisplay,
Kalle Raitabbdcf1f2017-05-22 15:47:46 -0700575 HAL_PIXEL_FORMAT_RGBA_8888,
576 hasWideColorDisplay ? RenderEngine::WIDE_COLOR_SUPPORT : 0);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800577 }
578
579 // Drop the state lock while we initialize the hardware composer. We drop
580 // the lock because on creation, it will call back into SurfaceFlinger to
581 // initialize the primary display.
Steven Thomas050b2c82017-03-06 11:45:16 -0800582 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
583 "Starting with vr flinger active is not currently supported.");
Steven Thomas3cfac282017-02-06 12:29:30 -0800584 mRealHwc = new HWComposer(false);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800585 mHwc = mRealHwc;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800586 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
587
Jesse Hall692c7232012-11-08 15:41:56 -0800588 Mutex::Autolock _l(mStateLock);
589
Ian Elliott5c34de22017-04-10 14:42:30 -0600590 // Inform native graphics APIs whether the present timestamp is supported:
591 if (getHwComposer().hasCapability(
592 HWC2::Capability::PresentFenceIsNotReliable)) {
593 property_set(kTimestampProperty, "0");
594 } else {
595 property_set(kTimestampProperty, "1");
596 }
597
Steven Thomas050b2c82017-03-06 11:45:16 -0800598 if (useVrFlinger) {
599 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700600 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
Steven Thomas050b2c82017-03-06 11:45:16 -0800601 mVrFlingerRequestsDisplay = requestDisplay;
602 signalTransaction();
603 };
604 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
605 vrFlingerRequestDisplayCallback);
606 if (!mVrFlinger) {
607 ALOGE("Failed to start vrflinger");
608 }
609 }
610
Mathias Agopian875d8e12013-06-07 15:35:48 -0700611 // retrieve the EGL context that was selected/created
612 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700613
Mathias Agopianda27af92012-09-13 18:17:13 -0700614 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
615 "couldn't create EGLContext");
616
Dan Stoza9e56aa02015-11-02 13:00:03 -0800617 // make the GLContext current so that we can create textures when creating
618 // Layers (which may happens before we render something)
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700619 getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext);
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700620
Jamie Gennisd1700752013-10-14 12:22:52 -0700621 mEventControlThread = new EventControlThread(this);
622 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
623
Mathias Agopian92a979a2012-08-02 18:32:23 -0700624 // initialize our drawing state
625 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700626
Andy McFadden13a082e2012-08-24 10:16:42 -0700627 // set initial conditions (e.g. unblank default device)
628 initializeDisplays();
629
Dan Stoza4e637772016-07-28 13:31:51 -0700630 mRenderEngine->primeCache();
631
Wei Wangb254fa32017-01-31 17:43:23 -0800632 mStartBootAnimThread = new StartBootAnimThread();
633 if (mStartBootAnimThread->Start() != NO_ERROR) {
634 ALOGE("Run StartBootAnimThread failed!");
635 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800636
Dan Stoza9e56aa02015-11-02 13:00:03 -0800637 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700638}
639
Romain Guy11d63f42017-07-20 12:47:14 -0700640void SurfaceFlinger::readPersistentProperties() {
641 char value[PROPERTY_VALUE_MAX];
642
643 property_get("persist.sys.sf.color_saturation", value, "1.0");
644 mSaturation = atof(value);
645 ALOGV("Saturation is set to %.2f", mSaturation);
646}
647
Mathias Agopiana67e4182012-06-19 17:26:12 -0700648void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800649 // Start boot animation service by setting a property mailbox
650 // if property setting thread is already running, Start() will be just a NOP
651 mStartBootAnimThread->Start();
652 // Wait until property was set
653 if (mStartBootAnimThread->join() != NO_ERROR) {
654 ALOGE("Join StartBootAnimThread failed!");
655 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700656}
657
Mathias Agopian875d8e12013-06-07 15:35:48 -0700658size_t SurfaceFlinger::getMaxTextureSize() const {
659 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700660}
661
Mathias Agopian875d8e12013-06-07 15:35:48 -0700662size_t SurfaceFlinger::getMaxViewportDims() const {
663 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700664}
665
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800666// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800667
Jamie Gennis582270d2011-08-17 18:19:00 -0700668bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800669 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800670 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800671 return authenticateSurfaceTextureLocked(bufferProducer);
672}
673
674bool SurfaceFlinger::authenticateSurfaceTextureLocked(
675 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800676 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700677 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800678}
679
Brian Anderson6b376712017-04-04 10:51:39 -0700680status_t SurfaceFlinger::getSupportedFrameTimestamps(
681 std::vector<FrameEvent>* outSupported) const {
682 *outSupported = {
683 FrameEvent::REQUESTED_PRESENT,
684 FrameEvent::ACQUIRE,
685 FrameEvent::LATCH,
686 FrameEvent::FIRST_REFRESH_START,
687 FrameEvent::LAST_REFRESH_START,
688 FrameEvent::GPU_COMPOSITION_DONE,
689 FrameEvent::DEQUEUE_READY,
690 FrameEvent::RELEASE,
691 };
692 if (!getHwComposer().hasCapability(
693 HWC2::Capability::PresentFenceIsNotReliable)) {
694 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
695 }
696 return NO_ERROR;
697}
698
Dan Stoza7f7da322014-05-02 15:26:25 -0700699status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
700 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700701 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700702 return BAD_VALUE;
703 }
704
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500705 if (!display.get())
706 return NAME_NOT_FOUND;
707
Jesse Hall692c7232012-11-08 15:41:56 -0800708 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700709 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800710 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700711 type = i;
712 break;
713 }
714 }
715
716 if (type < 0) {
717 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700718 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700719
Mathias Agopian8b736f12012-08-13 17:54:26 -0700720 // TODO: Not sure if display density should handled by SF any longer
721 class Density {
722 static int getDensityFromProperty(char const* propName) {
723 char property[PROPERTY_VALUE_MAX];
724 int density = 0;
725 if (property_get(propName, property, NULL) > 0) {
726 density = atoi(property);
727 }
728 return density;
729 }
730 public:
731 static int getEmuDensity() {
732 return getDensityFromProperty("qemu.sf.lcd_density"); }
733 static int getBuildDensity() {
734 return getDensityFromProperty("ro.sf.lcd_density"); }
735 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700736
Dan Stoza7f7da322014-05-02 15:26:25 -0700737 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700738
Dan Stoza9e56aa02015-11-02 13:00:03 -0800739 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700740 DisplayInfo info = DisplayInfo();
741
Dan Stoza9e56aa02015-11-02 13:00:03 -0800742 float xdpi = hwConfig->getDpiX();
743 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700744
745 if (type == DisplayDevice::DISPLAY_PRIMARY) {
746 // The density of the device is provided by a build property
747 float density = Density::getBuildDensity() / 160.0f;
748 if (density == 0) {
749 // the build doesn't provide a density -- this is wrong!
750 // use xdpi instead
751 ALOGE("ro.sf.lcd_density must be defined as a build property");
752 density = xdpi / 160.0f;
753 }
754 if (Density::getEmuDensity()) {
755 // if "qemu.sf.lcd_density" is specified, it overrides everything
756 xdpi = ydpi = density = Density::getEmuDensity();
757 density /= 160.0f;
758 }
759 info.density = density;
760
761 // TODO: this needs to go away (currently needed only by webkit)
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000762 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
763 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700764 } else {
765 // TODO: where should this value come from?
766 static const int TV_DENSITY = 213;
767 info.density = TV_DENSITY / 160.0f;
768 info.orientation = 0;
769 }
770
Dan Stoza9e56aa02015-11-02 13:00:03 -0800771 info.w = hwConfig->getWidth();
772 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700773 info.xdpi = xdpi;
774 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800775 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900776 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800777
Andy McFadden91b2ca82014-06-13 14:04:23 -0700778 // This is how far in advance a buffer must be queued for
779 // presentation at a given time. If you want a buffer to appear
780 // on the screen at time N, you must submit the buffer before
781 // (N - presentationDeadline).
782 //
783 // Normally it's one full refresh period (to give SF a chance to
784 // latch the buffer), but this can be reduced by configuring a
785 // DispSync offset. Any additional delays introduced by the hardware
786 // composer or panel must be accounted for here.
787 //
788 // We add an additional 1ms to allow for processing time and
789 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800790 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800791 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700792
793 // All non-virtual displays are currently considered secure.
794 info.secure = true;
795
Michael Wright28f24d02016-07-12 13:30:53 -0700796 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700797 }
798
Dan Stoza7f7da322014-05-02 15:26:25 -0700799 return NO_ERROR;
800}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700801
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800802status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700803 DisplayStatInfo* stats) {
804 if (stats == NULL) {
805 return BAD_VALUE;
806 }
807
808 // FIXME for now we always return stats for the primary display
809 memset(stats, 0, sizeof(*stats));
810 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
811 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
812 return NO_ERROR;
813}
814
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700815int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800816 if (display == NULL) {
817 ALOGE("%s : display is NULL", __func__);
818 return BAD_VALUE;
819 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700820
821 sp<const DisplayDevice> device(getDisplayDevice(display));
Dan Stoza24a42e92015-03-09 10:04:11 -0700822 if (device != NULL) {
823 return device->getActiveConfig();
824 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700825
Dan Stoza24a42e92015-03-09 10:04:11 -0700826 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700827}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700828
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700829void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
830 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
831 this);
832 int32_t type = hw->getDisplayType();
833 int currentMode = hw->getActiveConfig();
834
835 if (mode == currentMode) {
836 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
837 return;
838 }
839
840 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
841 ALOGW("Trying to set config for virtual display");
842 return;
843 }
844
845 hw->setActiveConfig(mode);
846 getHwComposer().setActiveConfig(type, mode);
847}
848
849status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
850 class MessageSetActiveConfig: public MessageBase {
851 SurfaceFlinger& mFlinger;
852 sp<IBinder> mDisplay;
853 int mMode;
854 public:
855 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
856 int mode) :
857 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
858 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700859 Vector<DisplayInfo> configs;
860 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700861 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700862 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700863 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700864 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700865 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700866 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
867 if (hw == NULL) {
868 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700869 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700870 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
871 ALOGW("Attempt to set active config = %d for virtual display",
872 mMode);
873 } else {
874 mFlinger.setActiveConfigInternal(hw, mMode);
875 }
876 return true;
877 }
878 };
879 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
880 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700881 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700882}
Michael Wright28f24d02016-07-12 13:30:53 -0700883status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
884 Vector<android_color_mode_t>* outColorModes) {
885 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
886 return BAD_VALUE;
887 }
888
889 if (!display.get()) {
890 return NAME_NOT_FOUND;
891 }
892
893 int32_t type = NAME_NOT_FOUND;
894 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
895 if (display == mBuiltinDisplays[i]) {
896 type = i;
897 break;
898 }
899 }
900
901 if (type < 0) {
902 return type;
903 }
904
905 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
906 outColorModes->clear();
907 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
908
909 return NO_ERROR;
910}
911
912android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700913 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700914 if (device != nullptr) {
915 return device->getActiveColorMode();
916 }
917 return static_cast<android_color_mode_t>(BAD_VALUE);
918}
919
920void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
921 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700922 int32_t type = hw->getDisplayType();
923 android_color_mode_t currentMode = hw->getActiveColorMode();
924
925 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700926 return;
927 }
928
929 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
930 ALOGW("Trying to set config for virtual display");
931 return;
932 }
933
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600934 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
935 hw->getDisplayType());
936
Michael Wright28f24d02016-07-12 13:30:53 -0700937 hw->setActiveColorMode(mode);
938 getHwComposer().setActiveColorMode(type, mode);
939}
940
941
942status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
943 android_color_mode_t colorMode) {
944 class MessageSetActiveColorMode: public MessageBase {
945 SurfaceFlinger& mFlinger;
946 sp<IBinder> mDisplay;
947 android_color_mode_t mMode;
948 public:
949 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
950 android_color_mode_t mode) :
951 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
952 virtual bool handler() {
953 Vector<android_color_mode_t> modes;
954 mFlinger.getDisplayColorModes(mDisplay, &modes);
955 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
956 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600957 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
958 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700959 return true;
960 }
961 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
962 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600963 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
964 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700965 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600966 ALOGW("Attempt to set active color mode %s %d for virtual display",
967 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -0700968 } else {
969 mFlinger.setActiveColorModeInternal(hw, mMode);
970 }
971 return true;
972 }
973 };
974 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
975 postMessageSync(msg);
976 return NO_ERROR;
977}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700978
Svetoslavd85084b2014-03-20 10:28:31 -0700979status_t SurfaceFlinger::clearAnimationFrameStats() {
980 Mutex::Autolock _l(mStateLock);
981 mAnimFrameTracker.clearStats();
982 return NO_ERROR;
983}
984
985status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
986 Mutex::Autolock _l(mStateLock);
987 mAnimFrameTracker.getStats(outStats);
988 return NO_ERROR;
989}
990
Dan Stozac4f471e2016-03-24 09:31:08 -0700991status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
992 HdrCapabilities* outCapabilities) const {
993 Mutex::Autolock _l(mStateLock);
994
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700995 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -0700996 if (displayDevice == nullptr) {
997 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
998 return BAD_VALUE;
999 }
1000
1001 std::unique_ptr<HdrCapabilities> capabilities =
1002 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
1003 if (capabilities) {
1004 std::swap(*outCapabilities, *capabilities);
1005 } else {
1006 return BAD_VALUE;
1007 }
1008
1009 return NO_ERROR;
1010}
1011
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001012status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
1013 if (enable == mInjectVSyncs) {
1014 return NO_ERROR;
1015 }
1016
1017 if (enable) {
1018 mInjectVSyncs = enable;
1019 ALOGV("VSync Injections enabled");
1020 if (mVSyncInjector.get() == nullptr) {
1021 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -07001022 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001023 }
1024 mEventQueue.setEventThread(mInjectorEventThread);
1025 } else {
1026 mInjectVSyncs = enable;
1027 ALOGV("VSync Injections disabled");
1028 mEventQueue.setEventThread(mSFEventThread);
1029 mVSyncInjector.clear();
1030 }
1031 return NO_ERROR;
1032}
1033
1034status_t SurfaceFlinger::injectVSync(nsecs_t when) {
1035 if (!mInjectVSyncs) {
1036 ALOGE("VSync Injections not enabled");
1037 return BAD_VALUE;
1038 }
1039 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1040 ALOGV("Injecting VSync inside SurfaceFlinger");
1041 mVSyncInjector->onInjectSyncEvent(when);
1042 }
1043 return NO_ERROR;
1044}
1045
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001046// ----------------------------------------------------------------------------
1047
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001048sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1049 ISurfaceComposer::VsyncSource vsyncSource) {
1050 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1051 return mSFEventThread->createEventConnection();
1052 } else {
1053 return mEventThread->createEventConnection();
1054 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001055}
1056
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001057// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001058
1059void SurfaceFlinger::waitForEvent() {
1060 mEventQueue.waitMessage();
1061}
1062
1063void SurfaceFlinger::signalTransaction() {
1064 mEventQueue.invalidate();
1065}
1066
1067void SurfaceFlinger::signalLayerUpdate() {
1068 mEventQueue.invalidate();
1069}
1070
1071void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001072 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001073 mEventQueue.refresh();
1074}
1075
1076status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001077 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001078 return mEventQueue.postMessage(msg, reltime);
1079}
1080
1081status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001082 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001083 status_t res = mEventQueue.postMessage(msg, reltime);
1084 if (res == NO_ERROR) {
1085 msg->wait();
1086 }
1087 return res;
1088}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001089
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001090void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001091 do {
1092 waitForEvent();
1093 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001094}
1095
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001096void SurfaceFlinger::enableHardwareVsync() {
1097 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001098 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001099 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001100 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1101 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001102 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001103 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001104}
1105
Jesse Hall948fe0c2013-10-14 12:56:09 -07001106void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001107 Mutex::Autolock _l(mHWVsyncLock);
1108
Jesse Hall948fe0c2013-10-14 12:56:09 -07001109 if (makeAvailable) {
1110 mHWVsyncAvailable = true;
1111 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001112 // Hardware vsync is not currently available, so abort the resync
1113 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001114 return;
1115 }
1116
Dan Stoza9e56aa02015-11-02 13:00:03 -08001117 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1118 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001119
1120 mPrimaryDispSync.reset();
1121 mPrimaryDispSync.setPeriod(period);
1122
1123 if (!mPrimaryHWVsyncEnabled) {
1124 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001125 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1126 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001127 mPrimaryHWVsyncEnabled = true;
1128 }
1129}
1130
Jesse Hall948fe0c2013-10-14 12:56:09 -07001131void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001132 Mutex::Autolock _l(mHWVsyncLock);
1133 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001134 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1135 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001136 mPrimaryDispSync.endResync();
1137 mPrimaryHWVsyncEnabled = false;
1138 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001139 if (makeUnavailable) {
1140 mHWVsyncAvailable = false;
1141 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001142}
1143
Tim Murray4a4e4a22016-04-19 16:29:23 +00001144void SurfaceFlinger::resyncWithRateLimit() {
1145 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001146
1147 // No explicit locking is needed here since EventThread holds a lock while calling this method
1148 static nsecs_t sLastResyncAttempted = 0;
1149 const nsecs_t now = systemTime();
1150 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001151 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001152 }
Dan Stoza57164302017-05-08 14:03:54 -07001153 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001154}
1155
Steven Thomas3cfac282017-02-06 12:29:30 -08001156void SurfaceFlinger::onVSyncReceived(HWComposer* composer, int32_t type,
1157 nsecs_t timestamp) {
1158 Mutex::Autolock lock(mStateLock);
1159 // Ignore any vsyncs from the non-active hardware composer.
1160 if (composer != mHwc) {
1161 return;
1162 }
1163
Jamie Gennisd1700752013-10-14 12:22:52 -07001164 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001165
Jamie Gennisd1700752013-10-14 12:22:52 -07001166 { // Scope for the lock
1167 Mutex::Autolock _l(mHWVsyncLock);
1168 if (type == 0 && mPrimaryHWVsyncEnabled) {
1169 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001170 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001171 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001172
1173 if (needsHwVsync) {
1174 enableHardwareVsync();
1175 } else {
1176 disableHardwareVsync(false);
1177 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001178}
1179
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001180void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001181 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001182 *compositorTiming = mCompositorTiming;
1183}
1184
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001185void SurfaceFlinger::createDefaultDisplayDevice() {
1186 const int32_t type = DisplayDevice::DISPLAY_PRIMARY;
1187 wp<IBinder> token = mBuiltinDisplays[type];
1188
1189 // All non-virtual displays are currently considered secure.
1190 const bool isSecure = true;
1191
1192 sp<IGraphicBufferProducer> producer;
1193 sp<IGraphicBufferConsumer> consumer;
1194 BufferQueue::createBufferQueue(&producer, &consumer);
1195
1196 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1197
1198 bool hasWideColorModes = false;
1199 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1200 for (android_color_mode_t colorMode : modes) {
1201 switch (colorMode) {
1202 case HAL_COLOR_MODE_DISPLAY_P3:
1203 case HAL_COLOR_MODE_ADOBE_RGB:
1204 case HAL_COLOR_MODE_DCI_P3:
1205 hasWideColorModes = true;
1206 break;
1207 default:
1208 break;
1209 }
1210 }
1211 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
1212 token, fbs, producer, mRenderEngine->getEGLConfig(),
1213 hasWideColorModes && hasWideColorDisplay);
1214 mDisplays.add(token, hw);
1215 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
1216 if (hasWideColorModes && hasWideColorDisplay) {
1217 defaultColorMode = HAL_COLOR_MODE_SRGB;
1218 }
1219 setActiveColorModeInternal(hw, defaultColorMode);
1220}
1221
1222void SurfaceFlinger::onHotplugReceived(HWComposer* composer, int32_t disp, bool connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001223 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001224
1225 if (composer->isUsingVrComposer()) {
1226 // We handle initializing the primary display device for the VR
1227 // window manager hwc explicitly at the time of transition.
1228 if (disp != DisplayDevice::DISPLAY_PRIMARY) {
1229 ALOGE("External displays are not supported by the vr hardware composer.");
1230 }
1231 return;
1232 }
1233
Dan Stoza9e56aa02015-11-02 13:00:03 -08001234 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1235 Mutex::Autolock lock(mStateLock);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001236 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1237 createDefaultDisplayDevice();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001238 } else {
1239 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001240 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001241 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001242 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001243 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001244 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1245 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001246 }
1247 setTransactionFlags(eDisplayTransactionNeeded);
1248
Andy McFadden9e9689c2012-10-10 18:17:51 -07001249 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001250 }
Mathias Agopian86303202012-07-24 22:46:10 -07001251}
1252
Steven Thomas3cfac282017-02-06 12:29:30 -08001253void SurfaceFlinger::onInvalidateReceived(HWComposer* composer) {
1254 Mutex::Autolock lock(mStateLock);
1255 if (composer == mHwc) {
1256 repaintEverything();
1257 } else {
1258 // This isn't from our current hardware composer. If it's a callback
1259 // from the real composer, forward the refresh request to vr
1260 // flinger. Otherwise ignore it.
1261 if (!composer->isUsingVrComposer()) {
1262 mVrFlinger->OnHardwareComposerRefresh();
1263 }
1264 }
1265}
1266
Dan Stoza9e56aa02015-11-02 13:00:03 -08001267void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001268 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001269 getHwComposer().setVsyncEnabled(disp,
1270 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001271}
1272
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001273// Note: it is assumed the caller holds |mStateLock| when this is called
1274void SurfaceFlinger::resetHwcLocked() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001275 disableHardwareVsync(true);
1276 clearHwcLayers(mDrawingState.layersSortedByZ);
1277 clearHwcLayers(mCurrentState.layersSortedByZ);
Steven Thomasf5a5f6e2017-07-17 13:59:23 -07001278 for (size_t disp = 0; disp < mDisplays.size(); ++disp) {
1279 clearHwcLayers(mDisplays[disp]->getVisibleLayersSortedByZ());
1280 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001281 // Clear the drawing state so that the logic inside of
1282 // handleTransactionLocked will fire. It will determine the delta between
1283 // mCurrentState and mDrawingState and re-apply all changes when we make the
1284 // transition.
1285 mDrawingState.displays.clear();
Alex Sakhartchoukda8490d2017-04-12 17:09:42 -04001286 // Release virtual display hwcId during vr mode transition.
1287 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1288 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1289 if (displayDevice->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL) {
1290 displayDevice->disconnect(getHwComposer());
1291 }
1292 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001293 mDisplays.clear();
1294}
1295
Steven Thomas050b2c82017-03-06 11:45:16 -08001296void SurfaceFlinger::updateVrFlinger() {
1297 if (!mVrFlinger)
1298 return;
1299 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1300 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001301 return;
1302 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001303
Steven Thomas050b2c82017-03-06 11:45:16 -08001304 if (vrFlingerRequestsDisplay && !mVrHwc) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001305 // Construct new HWComposer without holding any locks.
1306 mVrHwc = new HWComposer(true);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001307
1308 // Set up the event handlers. This step is neccessary to initialize the internal state of
1309 // the hardware composer object properly. Our callbacks are designed such that if they are
1310 // triggered between now and the point where the display is properly re-initialized, they
1311 // will not have any effect, so this is safe to do here, before the lock is aquired.
1312 mVrHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
Mark Urbanus209beca2017-02-23 11:16:04 -08001313 ALOGV("Vr HWC created");
1314 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001315
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001316 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001317
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001318 if (vrFlingerRequestsDisplay) {
1319 resetHwcLocked();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001320
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001321 mHwc = mVrHwc;
1322 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001323
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001324 } else {
1325 mVrFlinger->SeizeDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001326
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001327 resetHwcLocked();
1328
1329 mHwc = mRealHwc;
1330 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001331 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001332
1333 mVisibleRegionsDirty = true;
1334 invalidateHwcGeometry();
1335
1336 // Explicitly re-initialize the primary display. This is because some other
1337 // parts of this class rely on the primary display always being available.
1338 createDefaultDisplayDevice();
1339
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001340 // Re-enable default display.
1341 sp<LambdaMessage> requestMessage = new LambdaMessage([&]() {
1342 sp<DisplayDevice> hw(getDisplayDevice(mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1343 setPowerModeInternal(hw, HWC_POWER_MODE_NORMAL);
1344
1345 // Reset the timing values to account for the period of the swapped in HWC
1346 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1347 const nsecs_t period = activeConfig->getVsyncPeriod();
1348 mAnimFrameTracker.setDisplayRefreshPeriod(period);
1349
1350 // Use phase of 0 since phase is not known.
1351 // Use latency of 0, which will snap to the ideal latency.
1352 setCompositorTimingSnapped(0, period, 0);
1353 });
1354 postMessageAsync(requestMessage);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001355
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001356 android_atomic_or(1, &mRepaintEverything);
1357 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001358}
1359
Mathias Agopian4fec8732012-06-29 14:12:52 -07001360void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001361 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001362 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001363 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001364 bool frameMissed = !mHadClientComposition &&
1365 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001366 (mPreviousPresentFence->getSignalTime() ==
1367 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001368 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001369 if (mPropagateBackpressure && frameMissed) {
Fabien Sanglardaf5b6b82017-02-23 11:17:11 -08001370 ALOGD("Backpressure trigger, skipping transaction & refresh!");
Dan Stoza50182882016-07-08 12:02:20 -07001371 signalLayerUpdate();
1372 break;
1373 }
1374
Steven Thomas050b2c82017-03-06 11:45:16 -08001375 // Now that we're going to make it to the handleMessageTransaction()
1376 // call below it's safe to call updateVrFlinger(), which will
1377 // potentially trigger a display handoff.
1378 updateVrFlinger();
1379
Dan Stoza6b9454d2014-11-07 16:00:59 -08001380 bool refreshNeeded = handleMessageTransaction();
1381 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001382 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001383 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001384 // Signal a refresh if a transaction modified the window state,
1385 // a new buffer was latched, or if HWC has requested a full
1386 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001387 signalRefresh();
1388 }
1389 break;
1390 }
1391 case MessageQueue::REFRESH: {
1392 handleMessageRefresh();
1393 break;
1394 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001395 }
1396}
1397
Dan Stoza6b9454d2014-11-07 16:00:59 -08001398bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001399 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001400 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001401 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001402 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001403 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001404 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001405}
1406
Dan Stoza6b9454d2014-11-07 16:00:59 -08001407bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001408 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001409 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001410}
1411
1412void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001413 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001414
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001415 mRefreshPending = false;
1416
Pablo Ceballos40845df2016-01-25 17:41:15 -08001417 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001418
Brian Andersond6927fb2016-07-23 23:37:30 -07001419 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001420 rebuildLayerStacks();
1421 setUpHWComposer();
1422 doDebugFlashRegions();
1423 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001424 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001425
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001426 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001427
1428 mHadClientComposition = false;
1429 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1430 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1431 mHadClientComposition = mHadClientComposition ||
1432 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1433 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001434
Dan Stoza9e56aa02015-11-02 13:00:03 -08001435 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001436}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001437
Mathias Agopiancd60f992012-08-16 16:28:27 -07001438void SurfaceFlinger::doDebugFlashRegions()
1439{
1440 // is debugging enabled
1441 if (CC_LIKELY(!mDebugRegion))
1442 return;
1443
1444 const bool repaintEverything = mRepaintEverything;
1445 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1446 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001447 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001448 // transform the dirty region into this screen's coordinate space
1449 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1450 if (!dirtyRegion.isEmpty()) {
1451 // redraw the whole screen
1452 doComposeSurfaces(hw, Region(hw->bounds()));
1453
1454 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001455 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001456 RenderEngine& engine(getRenderEngine());
1457 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1458
Mathias Agopianda27af92012-09-13 18:17:13 -07001459 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001460 }
1461 }
1462 }
1463
1464 postFramebuffer();
1465
1466 if (mDebugRegion > 1) {
1467 usleep(mDebugRegion * 1000);
1468 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001469
Dan Stoza9e56aa02015-11-02 13:00:03 -08001470 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001471 auto& displayDevice = mDisplays[displayId];
1472 if (!displayDevice->isDisplayOn()) {
1473 continue;
1474 }
1475
1476 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001477 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1478 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001479 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001480}
1481
Brian Andersond6927fb2016-07-23 23:37:30 -07001482void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001483{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001484 ATRACE_CALL();
1485 ALOGV("preComposition");
1486
Mathias Agopiancd60f992012-08-16 16:28:27 -07001487 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001488 mDrawingState.traverseInZOrder([&](Layer* layer) {
1489 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001490 needExtraInvalidate = true;
1491 }
Robert Carr2047fae2016-11-28 14:09:09 -08001492 });
1493
Mathias Agopiancd60f992012-08-16 16:28:27 -07001494 if (needExtraInvalidate) {
1495 signalLayerUpdate();
1496 }
1497}
1498
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001499void SurfaceFlinger::updateCompositorTiming(
1500 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1501 std::shared_ptr<FenceTime>& presentFenceTime) {
1502 // Update queue of past composite+present times and determine the
1503 // most recently known composite to present latency.
1504 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1505 nsecs_t compositeToPresentLatency = -1;
1506 while (!mCompositePresentTimes.empty()) {
1507 CompositePresentTime& cpt = mCompositePresentTimes.front();
1508 // Cached values should have been updated before calling this method,
1509 // which helps avoid duplicate syscalls.
1510 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1511 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1512 break;
1513 }
1514 compositeToPresentLatency = displayTime - cpt.composite;
1515 mCompositePresentTimes.pop();
1516 }
1517
1518 // Don't let mCompositePresentTimes grow unbounded, just in case.
1519 while (mCompositePresentTimes.size() > 16) {
1520 mCompositePresentTimes.pop();
1521 }
1522
Brian Andersond0010582017-03-07 13:20:31 -08001523 setCompositorTimingSnapped(
1524 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1525}
1526
1527void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1528 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001529 // Integer division and modulo round toward 0 not -inf, so we need to
1530 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001531 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001532 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1533 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1534
Brian Andersond0010582017-03-07 13:20:31 -08001535 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1536 if (idealLatency <= 0) {
1537 idealLatency = vsyncInterval;
1538 }
1539
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001540 // Snap the latency to a value that removes scheduling jitter from the
1541 // composition and present times, which often have >1ms of jitter.
1542 // Reducing jitter is important if an app attempts to extrapolate
1543 // something (such as user input) to an accurate diasplay time.
1544 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1545 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001546 nsecs_t bias = vsyncInterval / 2;
1547 int64_t extraVsyncs =
1548 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1549 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1550 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001551
Brian Andersond0010582017-03-07 13:20:31 -08001552 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001553 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1554 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001555 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001556}
1557
1558void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001559{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001560 ATRACE_CALL();
1561 ALOGV("postComposition");
1562
Brian Anderson3546a3f2016-07-14 11:51:14 -07001563 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001564 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001565 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001566 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001567 }
1568
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001569 // |mStateLock| not needed as we are on the main thread
1570 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001571
1572 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1573 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1574 glCompositionDoneFenceTime =
1575 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1576 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1577 } else {
1578 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1579 }
1580 mGlCompositionDoneTimeline.updateSignalTimes();
1581
Brian Anderson4e606e32017-03-16 15:34:57 -07001582 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1583 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1584 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001585 mDisplayTimeline.updateSignalTimes();
1586
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001587 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1588 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1589
1590 // We use the refreshStartTime which might be sampled a little later than
1591 // when we started doing work for this frame, but that should be okay
1592 // since updateCompositorTiming has snapping logic.
1593 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001594 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001595 CompositorTiming compositorTiming;
1596 {
1597 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1598 compositorTiming = mCompositorTiming;
1599 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001600
Robert Carr2047fae2016-11-28 14:09:09 -08001601 mDrawingState.traverseInZOrder([&](Layer* layer) {
1602 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001603 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001604 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001605 recordBufferingStats(layer->getName().string(),
1606 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001607 }
Robert Carr2047fae2016-11-28 14:09:09 -08001608 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001609
Brian Anderson4e606e32017-03-16 15:34:57 -07001610 if (presentFence->isValid()) {
1611 if (mPrimaryDispSync.addPresentFence(presentFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001612 enableHardwareVsync();
1613 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001614 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001615 }
1616 }
1617
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001618 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001619 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001620 enableHardwareVsync();
1621 }
1622 }
1623
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001624 if (mAnimCompositionPending) {
1625 mAnimCompositionPending = false;
1626
Brian Anderson4e606e32017-03-16 15:34:57 -07001627 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001628 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001629 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001630 } else {
1631 // The HWC doesn't support present fences, so use the refresh
1632 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001633 nsecs_t presentTime =
1634 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001635 mAnimFrameTracker.setActualPresentTime(presentTime);
1636 }
1637 mAnimFrameTracker.advanceFrame();
1638 }
Dan Stozab90cf072015-03-05 11:05:59 -08001639
1640 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1641 return;
1642 }
1643
1644 nsecs_t currentTime = systemTime();
1645 if (mHasPoweredOff) {
1646 mHasPoweredOff = false;
1647 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001648 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001649 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001650 if (numPeriods < NUM_BUCKETS - 1) {
1651 mFrameBuckets[numPeriods] += elapsedTime;
1652 } else {
1653 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1654 }
1655 mTotalTime += elapsedTime;
1656 }
1657 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001658}
1659
1660void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001661 ATRACE_CALL();
1662 ALOGV("rebuildLayerStacks");
1663
Mathias Agopiancd60f992012-08-16 16:28:27 -07001664 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001665 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1666 ATRACE_CALL();
1667 mVisibleRegionsDirty = false;
1668 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001669
Jeff Sharkey76488112017-02-27 14:15:18 -07001670 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1671 Region opaqueRegion;
1672 Region dirtyRegion;
1673 Vector<sp<Layer>> layersSortedByZ;
1674 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1675 const Transform& tr(displayDevice->getTransform());
1676 const Rect bounds(displayDevice->getBounds());
1677 if (displayDevice->isDisplayOn()) {
1678 computeVisibleRegions(
1679 displayDevice->getLayerStack(), dirtyRegion,
1680 opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001681
Jeff Sharkey76488112017-02-27 14:15:18 -07001682 mDrawingState.traverseInZOrder([&](Layer* layer) {
1683 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
1684 Region drawRegion(tr.transform(
1685 layer->visibleNonTransparentRegion));
1686 drawRegion.andSelf(bounds);
1687 if (!drawRegion.isEmpty()) {
1688 layersSortedByZ.add(layer);
1689 } else {
1690 // Clear out the HWC layer if this layer was
1691 // previously visible, but no longer is
1692 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1693 nullptr);
1694 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001695 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001696 // WM changes displayDevice->layerStack upon sleep/awake.
1697 // Here we make sure we delete the HWC layers even if
1698 // WM changed their layer stack.
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001699 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1700 nullptr);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001701 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001702 });
1703 }
1704 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1705 displayDevice->undefinedRegion.set(bounds);
1706 displayDevice->undefinedRegion.subtractSelf(
1707 tr.transform(opaqueRegion));
1708 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001709 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001710 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001711}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001712
Romain Guy0147a172017-06-01 13:53:56 -07001713mat4 SurfaceFlinger::computeSaturationMatrix() const {
1714 if (mSaturation == 1.0f) {
1715 return mat4();
1716 }
1717
1718 // Rec.709 luma coefficients
1719 float3 luminance{0.213f, 0.715f, 0.072f};
1720 luminance *= 1.0f - mSaturation;
1721 return mat4(
1722 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1723 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1724 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1725 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1726 );
1727}
1728
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001729// pickColorMode translates a given dataspace into the best available color mode.
1730// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001731android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001732 switch (dataSpace) {
1733 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1734 // system expects.
1735 case HAL_DATASPACE_UNKNOWN:
1736 case HAL_DATASPACE_SRGB:
1737 case HAL_DATASPACE_V0_SRGB:
1738 return HAL_COLOR_MODE_SRGB;
1739 break;
1740
1741 case HAL_DATASPACE_DISPLAY_P3:
1742 return HAL_COLOR_MODE_DISPLAY_P3;
1743 break;
1744
1745 default:
1746 // TODO (courtneygo): Do we want to assert an error here?
1747 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1748 dataSpace);
1749 return HAL_COLOR_MODE_SRGB;
1750 break;
1751 }
1752}
1753
Romain Guy0147a172017-06-01 13:53:56 -07001754android_dataspace SurfaceFlinger::bestTargetDataSpace(
1755 android_dataspace a, android_dataspace b) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001756 // Only support sRGB and Display-P3 right now.
1757 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1758 return HAL_DATASPACE_DISPLAY_P3;
1759 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001760 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1761 return HAL_DATASPACE_DISPLAY_P3;
1762 }
1763 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1764 return HAL_DATASPACE_DISPLAY_P3;
1765 }
1766
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001767 return HAL_DATASPACE_V0_SRGB;
1768}
1769
Mathias Agopiancd60f992012-08-16 16:28:27 -07001770void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001771 ATRACE_CALL();
1772 ALOGV("setUpHWComposer");
1773
Jesse Hall028dc8f2013-08-20 16:35:32 -07001774 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001775 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1776 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1777 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1778
1779 // If nothing has changed (!dirty), don't recompose.
1780 // If something changed, but we don't currently have any visible layers,
1781 // and didn't when we last did a composition, then skip it this time.
1782 // The second rule does two things:
1783 // - When all layers are removed from a display, we'll emit one black
1784 // frame, then nothing more until we get new layers.
1785 // - When a display is created with a private layer stack, we won't
1786 // emit any black frames until a layer is added to the layer stack.
1787 bool mustRecompose = dirty && !(empty && wasEmpty);
1788
1789 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1790 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1791 mustRecompose ? "doing" : "skipping",
1792 dirty ? "+" : "-",
1793 empty ? "+" : "-",
1794 wasEmpty ? "+" : "-");
1795
Dan Stoza71433162014-02-04 16:22:36 -08001796 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001797
1798 if (mustRecompose) {
1799 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1800 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001801 }
1802
Dan Stoza9e56aa02015-11-02 13:00:03 -08001803 // build the h/w work list
1804 if (CC_UNLIKELY(mGeometryInvalid)) {
1805 mGeometryInvalid = false;
1806 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1807 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1808 const auto hwcId = displayDevice->getHwcDisplayId();
1809 if (hwcId >= 0) {
1810 const Vector<sp<Layer>>& currentLayers(
1811 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001812 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001813 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001814 if (!layer->hasHwcLayer(hwcId)) {
1815 auto hwcLayer = mHwc->createLayer(hwcId);
1816 if (hwcLayer) {
1817 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1818 } else {
1819 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001820 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001821 }
1822 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001823
Robert Carrae060832016-11-28 10:51:00 -08001824 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001825 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001826 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001827 }
1828 }
1829 }
1830 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001831 }
Riley Andrews03414a12014-07-01 14:22:59 -07001832
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001833
Romain Guy0147a172017-06-01 13:53:56 -07001834 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001835
Dan Stoza9e56aa02015-11-02 13:00:03 -08001836 // Set the per-frame data
1837 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1838 auto& displayDevice = mDisplays[displayId];
1839 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001840
Dan Stoza9e56aa02015-11-02 13:00:03 -08001841 if (hwcId < 0) {
1842 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001843 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001844 if (colorMatrix != mPreviousColorMatrix) {
1845 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1846 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1847 "display %zd: %d", displayId, result);
1848 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001849 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1850 layer->setPerFrameData(displayDevice);
1851 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001852
1853 if (hasWideColorDisplay) {
1854 android_color_mode newColorMode;
1855 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1856
1857 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1858 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1859 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1860 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1861 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1862 }
1863 newColorMode = pickColorMode(newDataSpace);
1864
1865 setActiveColorModeInternal(displayDevice, newColorMode);
1866 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001867 }
1868
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001869 mPreviousColorMatrix = colorMatrix;
1870
Dan Stoza9e56aa02015-11-02 13:00:03 -08001871 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001872 auto& displayDevice = mDisplays[displayId];
1873 if (!displayDevice->isDisplayOn()) {
1874 continue;
1875 }
1876
1877 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001878 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1879 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001880 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001881}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001882
Mathias Agopiancd60f992012-08-16 16:28:27 -07001883void SurfaceFlinger::doComposition() {
1884 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001885 ALOGV("doComposition");
1886
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001887 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001888 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001889 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001890 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001891 // transform the dirty region into this screen's coordinate space
1892 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001893
1894 // repaint the framebuffer (if needed)
1895 doDisplayComposition(hw, dirtyRegion);
1896
Mathias Agopiancd60f992012-08-16 16:28:27 -07001897 hw->dirtyRegion.clear();
1898 hw->flip(hw->swapRegion);
1899 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001900 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001901 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001902 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001903}
1904
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001905void SurfaceFlinger::postFramebuffer()
1906{
Mathias Agopian841cde52012-03-01 15:44:37 -08001907 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001908 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001909
Mathias Agopiana44b0412011-10-16 18:46:35 -07001910 const nsecs_t now = systemTime();
1911 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001912
Dan Stoza9e56aa02015-11-02 13:00:03 -08001913 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1914 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001915 if (!displayDevice->isDisplayOn()) {
1916 continue;
1917 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001918 const auto hwcId = displayDevice->getHwcDisplayId();
1919 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001920 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001921 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001922 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001923 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001924 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1925 sp<Fence> releaseFence = Fence::NO_FENCE;
1926 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1927 releaseFence = displayDevice->getClientTargetAcquireFence();
1928 } else {
1929 auto hwcLayer = layer->getHwcLayer(hwcId);
1930 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001931 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001932 layer->onLayerDisplayed(releaseFence);
1933 }
1934 if (hwcId >= 0) {
1935 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001936 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001937 }
1938
Mathias Agopiana44b0412011-10-16 18:46:35 -07001939 mLastSwapBufferTime = systemTime() - now;
1940 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001941
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001942 // |mStateLock| not needed as we are on the main thread
1943 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07001944 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1945 logFrameStats();
1946 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001947}
1948
Mathias Agopian87baae12012-07-31 12:38:26 -07001949void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001950{
Mathias Agopian841cde52012-03-01 15:44:37 -08001951 ATRACE_CALL();
1952
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001953 // here we keep a copy of the drawing state (that is the state that's
1954 // going to be overwritten by handleTransactionLocked()) outside of
1955 // mStateLock so that the side-effects of the State assignment
1956 // don't happen with mStateLock held (which can cause deadlocks).
1957 State drawingState(mDrawingState);
1958
Mathias Agopianca4d3602011-05-19 15:38:14 -07001959 Mutex::Autolock _l(mStateLock);
1960 const nsecs_t now = systemTime();
1961 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001962
Mathias Agopianca4d3602011-05-19 15:38:14 -07001963 // Here we're guaranteed that some transaction flags are set
1964 // so we can call handleTransactionLocked() unconditionally.
1965 // We call getTransactionFlags(), which will also clear the flags,
1966 // with mStateLock held to guarantee that mCurrentState won't change
1967 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001968
Mathias Agopiane57f2922012-08-09 16:29:12 -07001969 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001970 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001971
Mathias Agopianca4d3602011-05-19 15:38:14 -07001972 mLastTransactionTime = systemTime() - now;
1973 mDebugInTransaction = 0;
1974 invalidateHwcGeometry();
1975 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001976}
1977
Mathias Agopian87baae12012-07-31 12:38:26 -07001978void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001979{
Dan Stoza7dde5992015-05-22 09:51:44 -07001980 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001981 mCurrentState.traverseInZOrder([](Layer* layer) {
1982 layer->notifyAvailableFrames();
1983 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001984
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001985 /*
1986 * Traversal of the children
1987 * (perform the transaction for each of them if needed)
1988 */
1989
Mathias Agopian3559b072012-08-15 13:46:03 -07001990 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001991 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001992 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001993 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001994
1995 const uint32_t flags = layer->doTransaction(0);
1996 if (flags & Layer::eVisibleRegion)
1997 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001998 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001999 }
2000
2001 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002002 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002003 */
2004
Mathias Agopiane57f2922012-08-09 16:29:12 -07002005 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002006 // here we take advantage of Vector's copy-on-write semantics to
2007 // improve performance by skipping the transaction entirely when
2008 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07002009 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2010 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002011 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002012 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07002013 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07002014 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07002015
2016 // find the displays that were removed
2017 // (ie: in drawing state but not in current state)
2018 // also handle displays that changed
2019 // (ie: displays that are in both lists)
2020 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002021 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2022 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002023 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002024 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07002025 // Call makeCurrent() on the primary display so we can
2026 // be sure that nothing associated with this display
2027 // is current.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002028 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
Mathias Agopian875d8e12013-06-07 15:35:48 -07002029 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002030 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
Jesse Hall02d86562013-03-25 14:43:23 -07002031 if (hw != NULL)
2032 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07002033 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08002034 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07002035 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07002036 } else {
2037 ALOGW("trying to remove the main display");
2038 }
2039 } else {
2040 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07002041 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002042 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08002043 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2044 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07002045 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002046 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07002047 // recreating the DisplayDevice, so we just remove it
2048 // from the drawing state, so that it get re-added
2049 // below.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002050 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
Jesse Hall02d86562013-03-25 14:43:23 -07002051 if (hw != NULL)
2052 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07002053 mDisplays.removeItem(display);
2054 mDrawingState.displays.removeItemsAt(i);
2055 dc--; i--;
2056 // at this point we must loop to the next item
2057 continue;
2058 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002059
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002060 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07002061 if (disp != NULL) {
2062 if (state.layerStack != draw[i].layerStack) {
2063 disp->setLayerStack(state.layerStack);
2064 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002065 if ((state.orientation != draw[i].orientation)
2066 || (state.viewport != draw[i].viewport)
2067 || (state.frame != draw[i].frame))
2068 {
2069 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002070 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07002071 }
Michael Lentine47e45402014-07-18 15:34:25 -07002072 if (state.width != draw[i].width || state.height != draw[i].height) {
2073 disp->setDisplaySize(state.width, state.height);
2074 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002075 }
2076 }
2077 }
2078
2079 // find displays that were added
2080 // (ie: in current state but not in drawing state)
2081 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002082 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002083 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002084
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002085 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002086 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002087 sp<IGraphicBufferProducer> bqProducer;
2088 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian0556d792017-03-22 15:49:32 -07002089 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002090
Dan Stoza9e56aa02015-11-02 13:00:03 -08002091 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002092 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002093 // Virtual displays without a surface are dormant:
2094 // they have external state (layer stack, projection,
2095 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002096 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002097
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002098 // Allow VR composer to use virtual displays.
2099 if (mUseHwcVirtualDisplays || mHwc == mVrHwc) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002100 int width = 0;
2101 int status = state.surface->query(
2102 NATIVE_WINDOW_WIDTH, &width);
2103 ALOGE_IF(status != NO_ERROR,
2104 "Unable to query width (%d)", status);
2105 int height = 0;
2106 status = state.surface->query(
2107 NATIVE_WINDOW_HEIGHT, &height);
2108 ALOGE_IF(status != NO_ERROR,
2109 "Unable to query height (%d)", status);
2110 int intFormat = 0;
2111 status = state.surface->query(
2112 NATIVE_WINDOW_FORMAT, &intFormat);
2113 ALOGE_IF(status != NO_ERROR,
2114 "Unable to query format (%d)", status);
2115 auto format = static_cast<android_pixel_format_t>(
2116 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002117
Dan Stoza8cf150a2016-08-02 10:27:31 -07002118 mHwc->allocateVirtualDisplay(width, height, &format,
2119 &hwcId);
2120 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002121
Dan Stoza5cf424b2016-05-20 14:02:39 -07002122 // TODO: Plumb requested format back up to consumer
2123
Dan Stoza9e56aa02015-11-02 13:00:03 -08002124 sp<VirtualDisplaySurface> vds =
2125 new VirtualDisplaySurface(*mHwc,
2126 hwcId, state.surface, bqProducer,
2127 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002128
2129 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002130 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002131 }
2132 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002133 ALOGE_IF(state.surface!=NULL,
2134 "adding a supported display, but rendering "
2135 "surface is provided (%p), ignoring it",
2136 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002137
2138 hwcId = state.type;
2139 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2140 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002141 }
2142
2143 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002144 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002145 sp<DisplayDevice> hw =
2146 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2147 dispSurface, producer,
2148 mRenderEngine->getEGLConfig(),
2149 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002150 hw->setLayerStack(state.layerStack);
2151 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002152 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002153 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002154 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002155 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002156 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002157 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002158 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002159 }
2160 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002161 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002162 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002163
Mathias Agopian84300952012-11-21 16:02:13 -08002164 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2165 // The transform hint might have changed for some layers
2166 // (either because a display has changed, or because a layer
2167 // as changed).
2168 //
2169 // Walk through all the layers in currentLayers,
2170 // and update their transform hint.
2171 //
2172 // If a layer is visible only on a single display, then that
2173 // display is used to calculate the hint, otherwise we use the
2174 // default display.
2175 //
2176 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2177 // the hint is set before we acquire a buffer from the surface texture.
2178 //
2179 // NOTE: layer transactions have taken place already, so we use their
2180 // drawing state. However, SurfaceFlinger's own transaction has not
2181 // happened yet, so we must use the current state layer list
2182 // (soon to become the drawing state list).
2183 //
2184 sp<const DisplayDevice> disp;
2185 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002186 bool first = true;
2187 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002188 // NOTE: we rely on the fact that layers are sorted by
2189 // layerStack first (so we don't have to traverse the list
2190 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002191 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002192 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002193 currentlayerStack = layerStack;
2194 // figure out if this layerstack is mirrored
2195 // (more than one display) if so, pick the default display,
2196 // if not, pick the only display it's on.
2197 disp.clear();
2198 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2199 sp<const DisplayDevice> hw(mDisplays[dpy]);
2200 if (hw->getLayerStack() == currentlayerStack) {
2201 if (disp == NULL) {
2202 disp = hw;
2203 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002204 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002205 break;
2206 }
2207 }
2208 }
2209 }
Chet Haase91d25932013-04-11 15:24:55 -07002210 if (disp == NULL) {
2211 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2212 // redraw after transform hint changes. See bug 8508397.
2213
2214 // could be null when this layer is using a layerStack
2215 // that is not visible on any display. Also can occur at
2216 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002217 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002218 }
Chet Haase91d25932013-04-11 15:24:55 -07002219 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002220
2221 first = false;
2222 });
Mathias Agopian84300952012-11-21 16:02:13 -08002223 }
2224
2225
Mathias Agopian3559b072012-08-15 13:46:03 -07002226 /*
2227 * Perform our own transaction if needed
2228 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002229
2230 if (mLayersAdded) {
2231 mLayersAdded = false;
2232 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002233 mVisibleRegionsDirty = true;
2234 }
2235
2236 // some layers might have been removed, so
2237 // we need to update the regions they're exposing.
2238 if (mLayersRemoved) {
2239 mLayersRemoved = false;
2240 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002241 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002242 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002243 // this layer is not visible anymore
2244 // TODO: we could traverse the tree from front to back and
2245 // compute the actual visible region
2246 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002247 Region visibleReg;
2248 visibleReg.set(layer->computeScreenBounds());
2249 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002250 }
Robert Carr2047fae2016-11-28 14:09:09 -08002251 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002252 }
2253
2254 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002255
2256 updateCursorAsync();
2257}
2258
2259void SurfaceFlinger::updateCursorAsync()
2260{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002261 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2262 auto& displayDevice = mDisplays[displayId];
2263 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002264 continue;
2265 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002266
2267 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2268 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002269 }
2270 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002271}
2272
2273void SurfaceFlinger::commitTransaction()
2274{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002275 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002276 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002277 for (const auto& l : mLayersPendingRemoval) {
2278 recordBufferingStats(l->getName().string(),
2279 l->getOccupancyHistory(true));
2280 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002281 }
2282 mLayersPendingRemoval.clear();
2283 }
2284
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002285 // If this transaction is part of a window animation then the next frame
2286 // we composite should be considered an animation as well.
2287 mAnimCompositionPending = mAnimTransactionPending;
2288
Mathias Agopian4fec8732012-06-29 14:12:52 -07002289 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002290 mDrawingState.traverseInZOrder([](Layer* layer) {
2291 layer->commitChildList();
2292 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002293 mTransactionPending = false;
2294 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002295 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002296}
2297
Robert Carr2047fae2016-11-28 14:09:09 -08002298void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07002299 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002300{
Mathias Agopian841cde52012-03-01 15:44:37 -08002301 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002302 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002303
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002304 Region aboveOpaqueLayers;
2305 Region aboveCoveredLayers;
2306 Region dirty;
2307
Mathias Agopian87baae12012-07-31 12:38:26 -07002308 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002309
Robert Carr2047fae2016-11-28 14:09:09 -08002310 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002311 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002312 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002313
Jesse Hall01e29052013-02-19 16:13:35 -08002314 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07002315 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08002316 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002317
Mathias Agopianab028732010-03-16 16:41:46 -07002318 /*
2319 * opaqueRegion: area of a surface that is fully opaque.
2320 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002321 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002322
2323 /*
2324 * visibleRegion: area of a surface that is visible on screen
2325 * and not fully transparent. This is essentially the layer's
2326 * footprint minus the opaque regions above it.
2327 * Areas covered by a translucent surface are considered visible.
2328 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002329 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002330
2331 /*
2332 * coveredRegion: area of a surface that is covered by all
2333 * visible regions above it (which includes the translucent areas).
2334 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002335 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002336
Jesse Halla8026d22012-09-25 13:25:04 -07002337 /*
2338 * transparentRegion: area of a surface that is hinted to be completely
2339 * transparent. This is only used to tell when the layer has no visible
2340 * non-transparent regions and can be removed from the layer list. It
2341 * does not affect the visibleRegion of this layer or any layers
2342 * beneath it. The hint may not be correct if apps don't respect the
2343 * SurfaceView restrictions (which, sadly, some don't).
2344 */
2345 Region transparentRegion;
2346
Mathias Agopianab028732010-03-16 16:41:46 -07002347
2348 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002349 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002350 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002351 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002352 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002353 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002354 if (!visibleRegion.isEmpty()) {
2355 // Remove the transparent area from the visible region
2356 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002357 if (tr.preserveRects()) {
2358 // transform the transparent region
2359 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002360 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002361 // transformation too complex, can't do the
2362 // transparent region optimization.
2363 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002364 }
Mathias Agopianab028732010-03-16 16:41:46 -07002365 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002366
Mathias Agopianab028732010-03-16 16:41:46 -07002367 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002368 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002369 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002370 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2371 // the opaque region is the layer's footprint
2372 opaqueRegion = visibleRegion;
2373 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002374 }
2375 }
2376
Mathias Agopianab028732010-03-16 16:41:46 -07002377 // Clip the covered region to the visible region
2378 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2379
2380 // Update aboveCoveredLayers for next (lower) layer
2381 aboveCoveredLayers.orSelf(visibleRegion);
2382
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002383 // subtract the opaque region covered by the layers above us
2384 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002385
2386 // compute this layer's dirty region
2387 if (layer->contentDirty) {
2388 // we need to invalidate the whole region
2389 dirty = visibleRegion;
2390 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002391 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002392 layer->contentDirty = false;
2393 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002394 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002395 * the exposed region consists of two components:
2396 * 1) what's VISIBLE now and was COVERED before
2397 * 2) what's EXPOSED now less what was EXPOSED before
2398 *
2399 * note that (1) is conservative, we start with the whole
2400 * visible region but only keep what used to be covered by
2401 * something -- which mean it may have been exposed.
2402 *
2403 * (2) handles areas that were not covered by anything but got
2404 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002405 */
Mathias Agopianab028732010-03-16 16:41:46 -07002406 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002407 const Region oldVisibleRegion = layer->visibleRegion;
2408 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002409 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2410 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002411 }
2412 dirty.subtractSelf(aboveOpaqueLayers);
2413
2414 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002415 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002416
Mathias Agopianab028732010-03-16 16:41:46 -07002417 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002418 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002419
Jesse Halla8026d22012-09-25 13:25:04 -07002420 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002421 layer->setVisibleRegion(visibleRegion);
2422 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002423 layer->setVisibleNonTransparentRegion(
2424 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002425 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002426
Mathias Agopian87baae12012-07-31 12:38:26 -07002427 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002428}
2429
Mathias Agopian87baae12012-07-31 12:38:26 -07002430void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2431 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002432 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002433 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2434 if (hw->getLayerStack() == layerStack) {
2435 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002436 }
2437 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002438}
2439
Dan Stoza6b9454d2014-11-07 16:00:59 -08002440bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002441{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002442 ALOGV("handlePageFlip");
2443
Brian Andersond6927fb2016-07-23 23:37:30 -07002444 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002445
Mathias Agopian4fec8732012-06-29 14:12:52 -07002446 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002447 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002448 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002449
2450 // Store the set of layers that need updates. This set must not change as
2451 // buffers are being latched, as this could result in a deadlock.
2452 // Example: Two producers share the same command stream and:
2453 // 1.) Layer 0 is latched
2454 // 2.) Layer 0 gets a new frame
2455 // 2.) Layer 1 gets a new frame
2456 // 3.) Layer 1 is latched.
2457 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2458 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002459 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002460 if (layer->hasQueuedFrame()) {
2461 frameQueued = true;
2462 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002463 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002464 } else {
2465 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002466 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002467 } else {
2468 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002469 }
Robert Carr2047fae2016-11-28 14:09:09 -08002470 });
2471
Dan Stoza9e56aa02015-11-02 13:00:03 -08002472 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002473 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002474 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002475 invalidateLayerStack(layer->getLayerStack(), dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002476 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002477 newDataLatched = true;
2478 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002479 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002480
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002481 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002482
2483 // If we will need to wake up at some time in the future to deal with a
2484 // queued frame that shouldn't be displayed during this vsync period, wake
2485 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002486 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002487 signalLayerUpdate();
2488 }
2489
2490 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002491 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002492}
2493
Mathias Agopianad456f92011-01-13 17:53:01 -08002494void SurfaceFlinger::invalidateHwcGeometry()
2495{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002496 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002497}
2498
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002499
Fabien Sanglard830b8472016-11-30 16:35:58 -08002500void SurfaceFlinger::doDisplayComposition(
2501 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002502 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002503{
Dan Stoza71433162014-02-04 16:22:36 -08002504 // We only need to actually compose the display if:
2505 // 1) It is being handled by hardware composer, which may need this to
2506 // keep its virtual display state machine in sync, or
2507 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002508 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002509 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002510 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002511 return;
2512 }
2513
Dan Stoza9e56aa02015-11-02 13:00:03 -08002514 ALOGV("doDisplayComposition");
2515
Mathias Agopian87baae12012-07-31 12:38:26 -07002516 Region dirtyRegion(inDirtyRegion);
2517
Mathias Agopianb8a55602009-06-26 19:06:36 -07002518 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002519 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002520
Fabien Sanglard830b8472016-11-30 16:35:58 -08002521 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002522 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002523 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2524 // takes a rectangle, we must make sure to update that whole
2525 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002526 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002527 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002528 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002529 // We need to redraw the rectangle that will be updated
2530 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002531 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002532 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002533 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002534 } else {
2535 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002536 dirtyRegion.set(displayDevice->bounds());
2537 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002538 }
2539 }
2540
Fabien Sanglard830b8472016-11-30 16:35:58 -08002541 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002542
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002543 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002544 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002545
2546 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002547 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002548}
2549
Dan Stoza9e56aa02015-11-02 13:00:03 -08002550bool SurfaceFlinger::doComposeSurfaces(
2551 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002552{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002553 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002554
Dan Stoza9e56aa02015-11-02 13:00:03 -08002555 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002556
2557 mat4 oldColorMatrix;
2558 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2559 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2560 if (applyColorMatrix) {
2561 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2562 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2563 }
2564
Dan Stoza9e56aa02015-11-02 13:00:03 -08002565 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2566 if (hasClientComposition) {
2567 ALOGV("hasClientComposition");
2568
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002569#ifdef USE_HWC2
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002570 mRenderEngine->setWideColor(displayDevice->getWideColorSupport());
Romain Guy88d37dd2017-05-26 17:57:05 -07002571 mRenderEngine->setColorMode(displayDevice->getActiveColorMode());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002572#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002573 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002574 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002575 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002576 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002577
2578 // |mStateLock| not needed as we are on the main thread
2579 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002580 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2581 }
2582 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002583 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002584
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002585 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002586 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2587 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002588 // when using overlays, we assume a fully transparent framebuffer
2589 // NOTE: we could reduce how much we need to clear, for instance
2590 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002591 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002592 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002593 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002594 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002595 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002596 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002597
2598 // we remove the scissor part
2599 // we're left with the letterbox region
2600 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002601 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002602
2603 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002604 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002605
2606 // but limit it to the dirty region
2607 region.andSelf(dirty);
2608
Mathias Agopianb9494d52012-04-18 02:28:45 -07002609 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002610 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002611 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002612 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002613 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002614 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002615
Dan Stoza9e56aa02015-11-02 13:00:03 -08002616 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002617 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002618 // scissor on the main display. It should never be needed
2619 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002620 const Rect& bounds(displayDevice->getBounds());
2621 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002622 if (scissor != bounds) {
2623 // scissor doesn't match the screen's dimensions, so we
2624 // need to clear everything outside of it and enable
2625 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002626
Mathias Agopianf45c5102012-10-24 16:29:17 -07002627 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002628 const uint32_t height = displayDevice->getHeight();
2629 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002630 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002631 }
2632 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002633 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002634
Mathias Agopian85d751c2012-08-29 16:59:24 -07002635 /*
2636 * and then, render the layers targeted at the framebuffer
2637 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002638
Dan Stoza9e56aa02015-11-02 13:00:03 -08002639 ALOGV("Rendering client layers");
2640 const Transform& displayTransform = displayDevice->getTransform();
2641 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002642 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002643 bool firstLayer = true;
2644 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2645 const Region clip(dirty.intersect(
2646 displayTransform.transform(layer->visibleRegion)));
2647 ALOGV("Layer: %s", layer->getName().string());
2648 ALOGV(" Composition type: %s",
2649 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002650 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002651 switch (layer->getCompositionType(hwcId)) {
2652 case HWC2::Composition::Cursor:
2653 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002654 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002655 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002656 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002657 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2658 layer->isOpaque(state) && (state.alpha == 1.0f)
2659 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002660 // never clear the very first layer since we're
2661 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002662 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002663 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002664 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002665 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002666 case HWC2::Composition::Client: {
2667 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002668 break;
2669 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002670 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002671 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002672 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002673 } else {
2674 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002675 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002676 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002677 }
2678 } else {
2679 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002680 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002681 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002682 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002683 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002684 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002685 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002686 }
2687 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002688
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002689 if (applyColorMatrix) {
2690 getRenderEngine().setupColorTransform(oldColorMatrix);
2691 }
2692
Mathias Agopianf45c5102012-10-24 16:29:17 -07002693 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002694 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002695 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002696}
2697
Fabien Sanglard830b8472016-11-30 16:35:58 -08002698void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2699 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002700 RenderEngine& engine(getRenderEngine());
2701 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002702}
2703
Dan Stoza7d89d062015-04-30 13:29:25 -07002704status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002705 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002706 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002707 const sp<Layer>& lbc,
2708 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002709{
Dan Stoza7d89d062015-04-30 13:29:25 -07002710 // add this layer to the current state list
2711 {
2712 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002713 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002714 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2715 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002716 return NO_MEMORY;
2717 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002718 if (parent == nullptr) {
2719 mCurrentState.layersSortedByZ.add(lbc);
2720 } else {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002721 if (mCurrentState.layersSortedByZ.indexOf(parent) < 0) {
2722 ALOGE("addClientLayer called with a removed parent");
2723 return NAME_NOT_FOUND;
2724 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002725 parent->addChild(lbc);
2726 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002727
Dan Stoza7d89d062015-04-30 13:29:25 -07002728 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002729 mLayersAdded = true;
2730 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002731 }
2732
Mathias Agopian96f08192010-06-02 23:28:45 -07002733 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002734 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002735
Dan Stoza7d89d062015-04-30 13:29:25 -07002736 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002737}
2738
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002739status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002740 Mutex::Autolock _l(mStateLock);
2741
Robert Carr1f0a16a2016-10-24 16:27:39 -07002742 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002743 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002744 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002745 if (topLevelOnly) {
2746 return NO_ERROR;
2747 }
2748
Chia-I Wu98f1c102017-05-30 14:54:08 -07002749 sp<Layer> ancestor = p;
2750 while (ancestor->getParent() != nullptr) {
2751 ancestor = ancestor->getParent();
2752 }
2753 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2754 ALOGE("removeLayer called with a layer whose parent has been removed");
2755 return NAME_NOT_FOUND;
2756 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002757
2758 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002759 } else {
2760 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002761 }
2762
Robert Carr136e2f62017-02-08 17:54:29 -08002763 // As a matter of normal operation, the LayerCleaner will produce a second
2764 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2765 // so we will succeed in promoting it, but it's already been removed
2766 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2767 // otherwise something has gone wrong and we are leaking the layer.
2768 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002769 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2770 layer->getName().string(),
2771 (p != nullptr) ? p->getName().string() : "no-parent");
2772 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002773 } else if (index < 0) {
2774 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002775 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002776
2777 mLayersPendingRemoval.add(layer);
2778 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002779 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002780 setTransactionFlags(eTransactionNeeded);
2781 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002782}
2783
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002784uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002785 return android_atomic_release_load(&mTransactionFlags);
2786}
2787
Mathias Agopian3f844832013-08-07 21:24:32 -07002788uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002789 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2790}
2791
Mathias Agopian3f844832013-08-07 21:24:32 -07002792uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002793 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2794 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002795 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002796 }
2797 return old;
2798}
2799
Mathias Agopian8b33f032012-07-24 20:43:54 -07002800void SurfaceFlinger::setTransactionState(
2801 const Vector<ComposerState>& state,
2802 const Vector<DisplayState>& displays,
2803 uint32_t flags)
2804{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002805 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002806 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002807 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002808
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002809 if (flags & eAnimation) {
2810 // For window updates that are part of an animation we must wait for
2811 // previous animation "frames" to be handled.
2812 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002813 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002814 if (CC_UNLIKELY(err != NO_ERROR)) {
2815 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002816 // caller after a few seconds.
2817 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2818 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002819 mAnimTransactionPending = false;
2820 break;
2821 }
2822 }
2823 }
2824
Mathias Agopiane57f2922012-08-09 16:29:12 -07002825 size_t count = displays.size();
2826 for (size_t i=0 ; i<count ; i++) {
2827 const DisplayState& s(displays[i]);
2828 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002829 }
2830
Mathias Agopiane57f2922012-08-09 16:29:12 -07002831 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002832 for (size_t i=0 ; i<count ; i++) {
2833 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002834 // Here we need to check that the interface we're given is indeed
2835 // one of our own. A malicious client could give us a NULL
2836 // IInterface, or one of its own or even one of our own but a
2837 // different type. All these situations would cause us to crash.
2838 //
2839 // NOTE: it would be better to use RTTI as we could directly check
2840 // that we have a Client*. however, RTTI is disabled in Android.
2841 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002842 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002843 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002844 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002845 sp<Client> client( static_cast<Client *>(s.client.get()) );
2846 transactionFlags |= setClientStateLocked(client, s.state);
2847 }
2848 }
2849 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002850 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002851
Robert Carr2a7dbb42016-05-24 11:41:28 -07002852 // If a synchronous transaction is explicitly requested without any changes,
2853 // force a transaction anyway. This can be used as a flush mechanism for
2854 // previous async transactions.
2855 if (transactionFlags == 0 && (flags & eSynchronous)) {
2856 transactionFlags = eTransactionNeeded;
2857 }
2858
Mathias Agopian386aa982011-11-07 21:58:03 -08002859 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002860 if (mInterceptor.isEnabled()) {
2861 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2862 }
Irvel468051e2016-06-13 16:44:44 -07002863
Mathias Agopian386aa982011-11-07 21:58:03 -08002864 // this triggers the transaction
2865 setTransactionFlags(transactionFlags);
2866
2867 // if this is a synchronous transaction, wait for it to take effect
2868 // before returning.
2869 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002870 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002871 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002872 if (flags & eAnimation) {
2873 mAnimTransactionPending = true;
2874 }
2875 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002876 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2877 if (CC_UNLIKELY(err != NO_ERROR)) {
2878 // just in case something goes wrong in SF, return to the
2879 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002880 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2881 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002882 break;
2883 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002884 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002885 }
2886}
2887
Mathias Agopiane57f2922012-08-09 16:29:12 -07002888uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2889{
Jesse Hall9a143922012-10-04 16:29:19 -07002890 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2891 if (dpyIdx < 0)
2892 return 0;
2893
Mathias Agopiane57f2922012-08-09 16:29:12 -07002894 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002895 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002896 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002897 const uint32_t what = s.what;
2898 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002899 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002900 disp.surface = s.surface;
2901 flags |= eDisplayTransactionNeeded;
2902 }
2903 }
2904 if (what & DisplayState::eLayerStackChanged) {
2905 if (disp.layerStack != s.layerStack) {
2906 disp.layerStack = s.layerStack;
2907 flags |= eDisplayTransactionNeeded;
2908 }
2909 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002910 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002911 if (disp.orientation != s.orientation) {
2912 disp.orientation = s.orientation;
2913 flags |= eDisplayTransactionNeeded;
2914 }
2915 if (disp.frame != s.frame) {
2916 disp.frame = s.frame;
2917 flags |= eDisplayTransactionNeeded;
2918 }
2919 if (disp.viewport != s.viewport) {
2920 disp.viewport = s.viewport;
2921 flags |= eDisplayTransactionNeeded;
2922 }
2923 }
Michael Lentine47e45402014-07-18 15:34:25 -07002924 if (what & DisplayState::eDisplaySizeChanged) {
2925 if (disp.width != s.width) {
2926 disp.width = s.width;
2927 flags |= eDisplayTransactionNeeded;
2928 }
2929 if (disp.height != s.height) {
2930 disp.height = s.height;
2931 flags |= eDisplayTransactionNeeded;
2932 }
2933 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002934 }
2935 return flags;
2936}
2937
2938uint32_t SurfaceFlinger::setClientStateLocked(
2939 const sp<Client>& client,
2940 const layer_state_t& s)
2941{
2942 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002943 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002944 if (layer != 0) {
2945 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002946 bool geometryAppliesWithResize =
2947 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002948 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002949 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002950 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002951 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002952 }
2953 if (what & layer_state_t::eLayerChanged) {
2954 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002955 const auto& p = layer->getParent();
2956 if (p == nullptr) {
2957 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2958 if (layer->setLayer(s.z) && idx >= 0) {
2959 mCurrentState.layersSortedByZ.removeAt(idx);
2960 mCurrentState.layersSortedByZ.add(layer);
2961 // we need traversal (state changed)
2962 // AND transaction (list changed)
2963 flags |= eTransactionNeeded|eTraversalNeeded;
2964 }
2965 } else {
2966 if (p->setChildLayer(layer, s.z)) {
2967 flags |= eTransactionNeeded|eTraversalNeeded;
2968 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002969 }
2970 }
Robert Carrdb66e622017-04-10 16:55:57 -07002971 if (what & layer_state_t::eRelativeLayerChanged) {
2972 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z)) {
2973 flags |= eTransactionNeeded|eTraversalNeeded;
2974 }
2975 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002976 if (what & layer_state_t::eSizeChanged) {
2977 if (layer->setSize(s.w, s.h)) {
2978 flags |= eTraversalNeeded;
2979 }
2980 }
2981 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002982 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002983 flags |= eTraversalNeeded;
2984 }
2985 if (what & layer_state_t::eMatrixChanged) {
2986 if (layer->setMatrix(s.matrix))
2987 flags |= eTraversalNeeded;
2988 }
2989 if (what & layer_state_t::eTransparentRegionChanged) {
2990 if (layer->setTransparentRegionHint(s.transparentRegion))
2991 flags |= eTraversalNeeded;
2992 }
Dan Stoza23116082015-06-18 14:58:39 -07002993 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002994 if (layer->setFlags(s.flags, s.mask))
2995 flags |= eTraversalNeeded;
2996 }
2997 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002998 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002999 flags |= eTraversalNeeded;
3000 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003001 if (what & layer_state_t::eFinalCropChanged) {
Robert Carr8d5227b2017-03-16 15:41:03 -07003002 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003003 flags |= eTraversalNeeded;
3004 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003005 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003006 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003007 // We only allow setting layer stacks for top level layers,
3008 // everything else inherits layer stack from its parent.
3009 if (layer->hasParent()) {
3010 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3011 layer->getName().string());
3012 } else if (idx < 0) {
3013 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3014 "that also does not appear in the top level layer list. Something"
3015 " has gone wrong.", layer->getName().string());
3016 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003017 mCurrentState.layersSortedByZ.removeAt(idx);
3018 mCurrentState.layersSortedByZ.add(layer);
3019 // we need traversal (state changed)
3020 // AND transaction (list changed)
3021 flags |= eTransactionNeeded|eTraversalNeeded;
3022 }
3023 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003024 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08003025 if (s.barrierHandle != nullptr) {
3026 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3027 } else if (s.barrierGbp != nullptr) {
3028 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3029 if (authenticateSurfaceTextureLocked(gbp)) {
3030 const auto& otherLayer =
3031 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3032 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3033 } else {
3034 ALOGE("Attempt to defer transaction to to an"
3035 " unrecognized GraphicBufferProducer");
3036 }
3037 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003038 // We don't trigger a traversal here because if no other state is
3039 // changed, we don't want this to cause any more work
3040 }
Robert Carr1db73f62016-12-21 12:58:51 -08003041 if (what & layer_state_t::eReparentChildren) {
3042 if (layer->reparentChildren(s.reparentHandle)) {
3043 flags |= eTransactionNeeded|eTraversalNeeded;
3044 }
3045 }
Robert Carr9524cb32017-02-13 11:32:32 -08003046 if (what & layer_state_t::eDetachChildren) {
3047 layer->detachChildren();
3048 }
Robert Carrc3574f72016-03-24 12:19:32 -07003049 if (what & layer_state_t::eOverrideScalingModeChanged) {
3050 layer->setOverrideScalingMode(s.overrideScalingMode);
3051 // We don't trigger a traversal here because if no other state is
3052 // changed, we don't want this to cause any more work
3053 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003054 }
3055 return flags;
3056}
3057
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003058status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003059 const String8& name,
3060 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003061 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003062 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3063 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003064{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003065 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003066 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003067 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003068 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003069 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003070
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003071 status_t result = NO_ERROR;
3072
3073 sp<Layer> layer;
3074
Cody Northropbc755282017-03-31 12:00:08 -06003075 String8 uniqueName = getUniqueLayerName(name);
3076
Mathias Agopian3165cc22012-08-08 19:42:09 -07003077 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3078 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003079 result = createNormalLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003080 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003081 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003082 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07003083 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003084 result = createDimLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003085 uniqueName, w, h, flags,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003086 handle, gbp, &layer);
3087 break;
3088 default:
3089 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003090 break;
3091 }
3092
Dan Stoza7d89d062015-04-30 13:29:25 -07003093 if (result != NO_ERROR) {
3094 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003095 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003096
Albert Chaulk479c60c2017-01-27 14:21:34 -05003097 layer->setInfo(windowType, ownerUid);
3098
Robert Carr1f0a16a2016-10-24 16:27:39 -07003099 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003100 if (result != NO_ERROR) {
3101 return result;
3102 }
Irvelffc9efc2016-07-27 15:16:37 -07003103 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003104
3105 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003106 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003107}
3108
Cody Northropbc755282017-03-31 12:00:08 -06003109String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3110{
3111 bool matchFound = true;
3112 uint32_t dupeCounter = 0;
3113
3114 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3115 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3116
3117 // Loop over layers until we're sure there is no matching name
3118 while (matchFound) {
3119 matchFound = false;
3120 mDrawingState.traverseInZOrder([&](Layer* layer) {
3121 if (layer->getName() == uniqueName) {
3122 matchFound = true;
3123 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3124 }
3125 });
3126 }
3127
3128 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3129
3130 return uniqueName;
3131}
3132
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003133status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
3134 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3135 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003136{
3137 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003138 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003139 case PIXEL_FORMAT_TRANSPARENT:
3140 case PIXEL_FORMAT_TRANSLUCENT:
3141 format = PIXEL_FORMAT_RGBA_8888;
3142 break;
3143 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003144 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003145 break;
3146 }
3147
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003148 *outLayer = new Layer(this, client, name, w, h, flags);
3149 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
3150 if (err == NO_ERROR) {
3151 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003152 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003153 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003154
3155 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3156 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003157}
3158
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003159status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
3160 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3161 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003162{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003163 *outLayer = new LayerDim(this, client, name, w, h, flags);
3164 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003165 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003166 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003167}
3168
Mathias Agopianac9fa422013-02-11 16:40:36 -08003169status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003170{
Robert Carr9524cb32017-02-13 11:32:32 -08003171 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003172 status_t err = NO_ERROR;
3173 sp<Layer> l(client->getLayerUser(handle));
3174 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003175 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003176 err = removeLayer(l);
3177 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3178 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003179 }
3180 return err;
3181}
3182
Mathias Agopian13127d82013-03-05 17:47:11 -08003183status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003184{
Mathias Agopian67106042013-03-14 19:18:13 -07003185 // called by ~LayerCleaner() when all references to the IBinder (handle)
3186 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003187 sp<Layer> l = layer.promote();
3188 if (l == nullptr) {
3189 // The layer has already been removed, carry on
3190 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003191 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003192 // If we have a parent, then we can continue to live as long as it does.
3193 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003194}
3195
Mathias Agopianb60314a2012-04-10 22:09:54 -07003196// ---------------------------------------------------------------------------
3197
Andy McFadden13a082e2012-08-24 10:16:42 -07003198void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003199 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003200 Vector<ComposerState> state;
3201 Vector<DisplayState> displays;
3202 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003203 d.what = DisplayState::eDisplayProjectionChanged |
3204 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003205 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003206 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003207 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003208 d.frame.makeInvalid();
3209 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003210 d.width = 0;
3211 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003212 displays.add(d);
3213 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003214 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003215
Dan Stoza9e56aa02015-11-02 13:00:03 -08003216 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3217 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003218 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003219
Brian Andersond0010582017-03-07 13:20:31 -08003220 // Use phase of 0 since phase is not known.
3221 // Use latency of 0, which will snap to the ideal latency.
3222 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003223}
3224
3225void SurfaceFlinger::initializeDisplays() {
3226 class MessageScreenInitialized : public MessageBase {
3227 SurfaceFlinger* flinger;
3228 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003229 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003230 virtual bool handler() {
3231 flinger->onInitializeDisplays();
3232 return true;
3233 }
3234 };
3235 sp<MessageBase> msg = new MessageScreenInitialized(this);
3236 postMessageAsync(msg); // we may be called from main thread, use async message
3237}
3238
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003239void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
3240 int mode) {
3241 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3242 this);
3243 int32_t type = hw->getDisplayType();
3244 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003245
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003246 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003247 return;
3248 }
3249
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003250 hw->setPowerMode(mode);
3251 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3252 ALOGW("Trying to set power mode for virtual display");
3253 return;
3254 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003255
Irvelffc9efc2016-07-27 15:16:37 -07003256 if (mInterceptor.isEnabled()) {
3257 Mutex::Autolock _l(mStateLock);
3258 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3259 if (idx < 0) {
3260 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3261 return;
3262 }
3263 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3264 }
3265
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003266 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003267 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003268 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003269 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3270 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003271 // FIXME: eventthread only knows about the main display right now
3272 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003273 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003274 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003275
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003276 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003277 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003278 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003279
3280 struct sched_param param = {0};
3281 param.sched_priority = 1;
3282 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3283 ALOGW("Couldn't set SCHED_FIFO on display on");
3284 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003285 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003286 // Turn off the display
3287 struct sched_param param = {0};
3288 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3289 ALOGW("Couldn't set SCHED_OTHER on display off");
3290 }
3291
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003292 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003293 disableHardwareVsync(true); // also cancels any in-progress resync
3294
Mathias Agopiancde87a32012-09-13 14:09:01 -07003295 // FIXME: eventthread only knows about the main display right now
3296 mEventThread->onScreenReleased();
3297 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003298
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003299 getHwComposer().setPowerMode(type, mode);
3300 mVisibleRegionsDirty = true;
3301 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003302 } else if (mode == HWC_POWER_MODE_DOZE ||
3303 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003304 // Update display while dozing
3305 getHwComposer().setPowerMode(type, mode);
3306 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3307 // FIXME: eventthread only knows about the main display right now
3308 mEventThread->onScreenAcquired();
3309 resyncToHardwareVsync(true);
3310 }
3311 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3312 // Leave display going to doze
3313 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3314 disableHardwareVsync(true); // also cancels any in-progress resync
3315 // FIXME: eventthread only knows about the main display right now
3316 mEventThread->onScreenReleased();
3317 }
3318 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003319 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003320 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003321 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003322 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003323}
3324
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003325void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3326 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003327 SurfaceFlinger& mFlinger;
3328 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003329 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003330 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003331 MessageSetPowerMode(SurfaceFlinger& flinger,
3332 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3333 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003334 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003335 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003336 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003337 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003338 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003339 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003340 ALOGW("Attempt to set power mode = %d for virtual display",
3341 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003342 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003343 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003344 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003345 return true;
3346 }
3347 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003348 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003349 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003350}
3351
3352// ---------------------------------------------------------------------------
3353
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003354status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3355{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003356 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003357
Mathias Agopianbd115332013-04-18 16:41:04 -07003358 IPCThreadState* ipc = IPCThreadState::self();
3359 const int pid = ipc->getCallingPid();
3360 const int uid = ipc->getCallingUid();
3361 if ((uid != AID_SHELL) &&
3362 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003363 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003364 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003365 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003366 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003367 // (this would indicate SF is stuck, but we want to be able to
3368 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003369 status_t err = mStateLock.timedLock(s2ns(1));
3370 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003371 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003372 result.appendFormat(
3373 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3374 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003375 }
3376
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003377 bool dumpAll = true;
3378 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003379 size_t numArgs = args.size();
3380 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003381 if ((index < numArgs) &&
3382 (args[index] == String16("--list"))) {
3383 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003384 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003385 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003386 }
3387
3388 if ((index < numArgs) &&
3389 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003390 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003391 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003392 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003393 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003394
3395 if ((index < numArgs) &&
3396 (args[index] == String16("--latency-clear"))) {
3397 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003398 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003399 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003400 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003401
3402 if ((index < numArgs) &&
3403 (args[index] == String16("--dispsync"))) {
3404 index++;
3405 mPrimaryDispSync.dump(result);
3406 dumpAll = false;
3407 }
Dan Stozab90cf072015-03-05 11:05:59 -08003408
3409 if ((index < numArgs) &&
3410 (args[index] == String16("--static-screen"))) {
3411 index++;
3412 dumpStaticScreenStats(result);
3413 dumpAll = false;
3414 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003415
3416 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003417 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003418 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003419 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003420 dumpAll = false;
3421 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003422
3423 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3424 index++;
3425 dumpWideColorInfo(result);
3426 dumpAll = false;
3427 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003428 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003429
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003430 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003431 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003432 }
3433
Mathias Agopian9795c422009-08-26 16:36:26 -07003434 if (locked) {
3435 mStateLock.unlock();
3436 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003437 }
3438 write(fd, result.string(), result.size());
3439 return NO_ERROR;
3440}
3441
Dan Stozac7014012014-02-14 15:03:43 -08003442void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3443 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003444{
Robert Carr2047fae2016-11-28 14:09:09 -08003445 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003446 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003447 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003448}
3449
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003450void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003451 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003452{
3453 String8 name;
3454 if (index < args.size()) {
3455 name = String8(args[index]);
3456 index++;
3457 }
3458
Dan Stoza9e56aa02015-11-02 13:00:03 -08003459 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3460 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003461 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003462
3463 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003464 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003465 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003466 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003467 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003468 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003469 }
Robert Carr2047fae2016-11-28 14:09:09 -08003470 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003471 }
3472}
3473
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003474void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003475 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003476{
3477 String8 name;
3478 if (index < args.size()) {
3479 name = String8(args[index]);
3480 index++;
3481 }
3482
Robert Carr2047fae2016-11-28 14:09:09 -08003483 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003484 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003485 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003486 }
Robert Carr2047fae2016-11-28 14:09:09 -08003487 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003488
Svetoslavd85084b2014-03-20 10:28:31 -07003489 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003490}
3491
Jamie Gennis6547ff42013-07-16 20:12:42 -07003492// This should only be called from the main thread. Otherwise it would need
3493// the lock and should use mCurrentState rather than mDrawingState.
3494void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003495 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003496 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003497 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003498
3499 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3500}
3501
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003502void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003503{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003504 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003505 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3506
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003507 if (isLayerTripleBufferingDisabled())
3508 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003509
3510 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003511 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003512 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003513 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003514 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3515 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003516 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003517}
3518
Dan Stozab90cf072015-03-05 11:05:59 -08003519void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3520{
3521 result.appendFormat("Static screen stats:\n");
3522 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3523 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3524 float percent = 100.0f *
3525 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3526 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3527 b + 1, bucketTimeSec, percent);
3528 }
3529 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3530 float percent = 100.0f *
3531 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3532 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3533 NUM_BUCKETS - 1, bucketTimeSec, percent);
3534}
3535
Dan Stozae77c7662016-05-13 11:37:28 -07003536void SurfaceFlinger::recordBufferingStats(const char* layerName,
3537 std::vector<OccupancyTracker::Segment>&& history) {
3538 Mutex::Autolock lock(mBufferingStatsMutex);
3539 auto& stats = mBufferingStats[layerName];
3540 for (const auto& segment : history) {
3541 if (!segment.usedThirdBuffer) {
3542 stats.twoBufferTime += segment.totalTime;
3543 }
3544 if (segment.occupancyAverage < 1.0f) {
3545 stats.doubleBufferedTime += segment.totalTime;
3546 } else if (segment.occupancyAverage < 2.0f) {
3547 stats.tripleBufferedTime += segment.totalTime;
3548 }
3549 ++stats.numSegments;
3550 stats.totalTime += segment.totalTime;
3551 }
3552}
3553
Brian Andersond6927fb2016-07-23 23:37:30 -07003554void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3555 result.appendFormat("Layer frame timestamps:\n");
3556
3557 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3558 const size_t count = currentLayers.size();
3559 for (size_t i=0 ; i<count ; i++) {
3560 currentLayers[i]->dumpFrameEvents(result);
3561 }
3562}
3563
Dan Stozae77c7662016-05-13 11:37:28 -07003564void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3565 result.append("Buffering stats:\n");
3566 result.append(" [Layer name] <Active time> <Two buffer> "
3567 "<Double buffered> <Triple buffered>\n");
3568 Mutex::Autolock lock(mBufferingStatsMutex);
3569 typedef std::tuple<std::string, float, float, float> BufferTuple;
3570 std::map<float, BufferTuple, std::greater<float>> sorted;
3571 for (const auto& statsPair : mBufferingStats) {
3572 const char* name = statsPair.first.c_str();
3573 const BufferingStats& stats = statsPair.second;
3574 if (stats.numSegments == 0) {
3575 continue;
3576 }
3577 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3578 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3579 stats.totalTime;
3580 float doubleBufferRatio = static_cast<float>(
3581 stats.doubleBufferedTime) / stats.totalTime;
3582 float tripleBufferRatio = static_cast<float>(
3583 stats.tripleBufferedTime) / stats.totalTime;
3584 sorted.insert({activeTime, {name, twoBufferRatio,
3585 doubleBufferRatio, tripleBufferRatio}});
3586 }
3587 for (const auto& sortedPair : sorted) {
3588 float activeTime = sortedPair.first;
3589 const BufferTuple& values = sortedPair.second;
3590 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3591 std::get<0>(values).c_str(), activeTime,
3592 std::get<1>(values), std::get<2>(values),
3593 std::get<3>(values));
3594 }
3595 result.append("\n");
3596}
3597
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003598void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3599 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
3600
3601 // TODO: print out if wide-color mode is active or not
3602
3603 for (size_t d = 0; d < mDisplays.size(); d++) {
3604 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3605 int32_t hwcId = displayDevice->getHwcDisplayId();
3606 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3607 continue;
3608 }
3609
3610 result.appendFormat("Display %d color modes:\n", hwcId);
3611 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3612 for (auto&& mode : modes) {
3613 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3614 }
3615
3616 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3617 result.appendFormat(" Current color mode: %s (%d)\n",
3618 decodeColorMode(currentMode).c_str(), currentMode);
3619 }
3620 result.append("\n");
3621}
3622
Mathias Agopian74d211a2013-04-22 16:55:35 +02003623void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3624 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003625{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003626 bool colorize = false;
3627 if (index < args.size()
3628 && (args[index] == String16("--color"))) {
3629 colorize = true;
3630 index++;
3631 }
3632
3633 Colorizer colorizer(colorize);
3634
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003635 // figure out if we're stuck somewhere
3636 const nsecs_t now = systemTime();
3637 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3638 const nsecs_t inTransaction(mDebugInTransaction);
3639 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3640 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3641
3642 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003643 * Dump library configuration.
3644 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003645
3646 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003647 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003648 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003649 appendSfConfigString(result);
3650 appendUiConfigString(result);
3651 appendGuiConfigString(result);
3652 result.append("\n");
3653
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003654 result.append("\nWide-Color information:\n");
3655 dumpWideColorInfo(result);
3656
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003657 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003658 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003659 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003660 result.append(SyncFeatures::getInstance().toString());
3661 result.append("\n");
3662
Dan Stoza9e56aa02015-11-02 13:00:03 -08003663 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3664
Andy McFadden41d67d72014-04-25 16:58:34 -07003665 colorizer.bold(result);
3666 result.append("DispSync configuration: ");
3667 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003668 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003669 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003670 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003671 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003672 result.append("\n");
3673
Dan Stozab90cf072015-03-05 11:05:59 -08003674 // Dump static screen stats
3675 result.append("\n");
3676 dumpStaticScreenStats(result);
3677 result.append("\n");
3678
Dan Stozae77c7662016-05-13 11:37:28 -07003679 dumpBufferingStats(result);
3680
Andy McFadden4803b742012-09-24 19:07:20 -07003681 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003682 * Dump the visible layer list
3683 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003684 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003685 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003686 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003687 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003688 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003689 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003690
3691 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003692 * Dump Display state
3693 */
3694
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003695 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003696 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003697 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003698 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3699 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003700 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003701 }
3702
3703 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003704 * Dump SurfaceFlinger global state
3705 */
3706
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003707 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003708 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003709 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003710
Mathias Agopian888c8222012-08-04 21:10:38 -07003711 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003712 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003713
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003714 colorizer.bold(result);
3715 result.appendFormat("EGL implementation : %s\n",
3716 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3717 colorizer.reset(result);
3718 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003719 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003720
Mathias Agopian875d8e12013-06-07 15:35:48 -07003721 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003722
Mathias Agopian42977342012-08-05 00:40:46 -07003723 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003724 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3725 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003726 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003727 " last eglSwapBuffers() time: %f us\n"
3728 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003729 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003730 " refresh-rate : %f fps\n"
3731 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003732 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003733 " gpu_to_cpu_unsupported : %d\n"
3734 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003735 mLastSwapBufferTime/1000.0,
3736 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003737 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003738 1e9 / activeConfig->getVsyncPeriod(),
3739 activeConfig->getDpiX(),
3740 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003741 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003742
Mathias Agopian74d211a2013-04-22 16:55:35 +02003743 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003744 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003745
Mathias Agopian74d211a2013-04-22 16:55:35 +02003746 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003747 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003748
3749 /*
3750 * VSYNC state
3751 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003752 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003753 result.append("\n");
3754
3755 /*
3756 * HWC layer minidump
3757 */
3758 for (size_t d = 0; d < mDisplays.size(); d++) {
3759 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3760 int32_t hwcId = displayDevice->getHwcDisplayId();
3761 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3762 continue;
3763 }
3764
3765 result.appendFormat("Display %d HWC layers:\n", hwcId);
3766 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003767 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003768 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003769 });
Dan Stozae22aec72016-08-01 13:20:59 -07003770 result.append("\n");
3771 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003772
3773 /*
3774 * Dump HWComposer state
3775 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003776 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003777 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003778 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003779 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003780 result.appendFormat(" h/w composer %s\n",
3781 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003782 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003783
3784 /*
3785 * Dump gralloc state
3786 */
3787 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3788 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07003789
3790 /*
3791 * Dump VrFlinger state if in use.
3792 */
3793 if (mVrFlingerRequestsDisplay && mVrFlinger) {
3794 result.append("VrFlinger state:\n");
3795 result.append(mVrFlinger->Dump().c_str());
3796 result.append("\n");
3797 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003798}
3799
Mathias Agopian13127d82013-03-05 17:47:11 -08003800const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003801SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003802 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003803 wp<IBinder> dpy;
3804 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3805 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3806 dpy = mDisplays.keyAt(i);
3807 break;
3808 }
3809 }
3810 if (dpy == NULL) {
3811 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3812 // Just use the primary display so we have something to return
3813 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3814 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003815 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003816}
3817
Keun young Park63f165f2012-08-31 10:53:36 -07003818bool SurfaceFlinger::startDdmConnection()
3819{
3820 void* libddmconnection_dso =
3821 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3822 if (!libddmconnection_dso) {
3823 return false;
3824 }
3825 void (*DdmConnection_start)(const char* name);
3826 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003827 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003828 if (!DdmConnection_start) {
3829 dlclose(libddmconnection_dso);
3830 return false;
3831 }
3832 (*DdmConnection_start)(getServiceName());
3833 return true;
3834}
3835
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003836status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003837 switch (code) {
3838 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003839 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003840 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003841 case CLEAR_ANIMATION_FRAME_STATS:
3842 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003843 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003844 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003845 {
3846 // codes that require permission check
3847 IPCThreadState* ipc = IPCThreadState::self();
3848 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003849 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003850 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003851 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003852 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003853 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003854 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003855 break;
3856 }
Robert Carr1db73f62016-12-21 12:58:51 -08003857 /*
3858 * Calling setTransactionState is safe, because you need to have been
3859 * granted a reference to Client* and Handle* to do anything with it.
3860 *
3861 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3862 */
3863 case SET_TRANSACTION_STATE:
3864 case CREATE_SCOPED_CONNECTION:
3865 {
3866 return OK;
3867 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003868 case CAPTURE_SCREEN:
3869 {
3870 // codes that require permission check
3871 IPCThreadState* ipc = IPCThreadState::self();
3872 const int pid = ipc->getCallingPid();
3873 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003874 if ((uid != AID_GRAPHICS) &&
3875 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003876 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003877 return PERMISSION_DENIED;
3878 }
3879 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003880 }
3881 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003882 return OK;
3883}
3884
3885status_t SurfaceFlinger::onTransact(
3886 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3887{
3888 status_t credentialCheck = CheckTransactCodeCredentials(code);
3889 if (credentialCheck != OK) {
3890 return credentialCheck;
3891 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003892
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003893 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3894 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003895 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07003896 IPCThreadState* ipc = IPCThreadState::self();
3897 const int uid = ipc->getCallingUid();
3898 if (CC_UNLIKELY(uid != AID_SYSTEM
3899 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003900 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003901 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003902 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003903 return PERMISSION_DENIED;
3904 }
3905 int n;
3906 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003907 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003908 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003909 return NO_ERROR;
3910 case 1002: // SHOW_UPDATES
3911 n = data.readInt32();
3912 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003913 invalidateHwcGeometry();
3914 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003915 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003916 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003917 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003918 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003919 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003920 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003921 setTransactionFlags(
3922 eTransactionNeeded|
3923 eDisplayTransactionNeeded|
3924 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003925 return NO_ERROR;
3926 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003927 case 1006:{ // send empty update
3928 signalRefresh();
3929 return NO_ERROR;
3930 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003931 case 1008: // toggle use of hw composer
3932 n = data.readInt32();
3933 mDebugDisableHWC = n ? 1 : 0;
3934 invalidateHwcGeometry();
3935 repaintEverything();
3936 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003937 case 1009: // toggle use of transform hint
3938 n = data.readInt32();
3939 mDebugDisableTransformHint = n ? 1 : 0;
3940 invalidateHwcGeometry();
3941 repaintEverything();
3942 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003943 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003944 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003945 reply->writeInt32(0);
3946 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003947 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003948 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003949 return NO_ERROR;
3950 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00003951 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07003952 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003953 return NO_ERROR;
3954 }
3955 case 1014: {
3956 // daltonize
3957 n = data.readInt32();
3958 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003959 case 1:
3960 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3961 break;
3962 case 2:
3963 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3964 break;
3965 case 3:
3966 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3967 break;
3968 default:
3969 mDaltonizer.setType(ColorBlindnessType::None);
3970 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003971 }
3972 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003973 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003974 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003975 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003976 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003977 invalidateHwcGeometry();
3978 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003979 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003980 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003981 case 1015: {
3982 // apply a color matrix
3983 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003984 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07003985 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07003986 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003987 for (size_t j = 0; j < 4; j++) {
3988 mColorMatrix[i][j] = data.readFloat();
3989 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003990 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003991 } else {
3992 mColorMatrix = mat4();
3993 }
Romain Guy88d37dd2017-05-26 17:57:05 -07003994
3995 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
3996 // the division by w in the fragment shader
3997 float4 lastRow(transpose(mColorMatrix)[3]);
3998 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
3999 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4000 }
4001
Alan Viverette9c5a3332013-09-12 20:04:35 -07004002 invalidateHwcGeometry();
4003 repaintEverything();
4004 return NO_ERROR;
4005 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004006 // This is an experimental interface
4007 // Needs to be shifted to proper binder interface when we productize
4008 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004009 n = data.readInt32();
4010 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004011 return NO_ERROR;
4012 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004013 case 1017: {
4014 n = data.readInt32();
4015 mForceFullDamage = static_cast<bool>(n);
4016 return NO_ERROR;
4017 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004018 case 1018: { // Modify Choreographer's phase offset
4019 n = data.readInt32();
4020 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4021 return NO_ERROR;
4022 }
4023 case 1019: { // Modify SurfaceFlinger's phase offset
4024 n = data.readInt32();
4025 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4026 return NO_ERROR;
4027 }
Irvel468051e2016-06-13 16:44:44 -07004028 case 1020: { // Layer updates interceptor
4029 n = data.readInt32();
4030 if (n) {
4031 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004032 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004033 }
4034 else{
4035 ALOGV("Interceptor disabled");
4036 mInterceptor.disable();
4037 }
4038 return NO_ERROR;
4039 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004040 case 1021: { // Disable HWC virtual displays
4041 n = data.readInt32();
4042 mUseHwcVirtualDisplays = !n;
4043 return NO_ERROR;
4044 }
Romain Guy0147a172017-06-01 13:53:56 -07004045 case 1022: { // Set saturation boost
4046 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4047
4048 invalidateHwcGeometry();
4049 repaintEverything();
4050 return NO_ERROR;
4051 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004052 }
4053 }
4054 return err;
4055}
4056
Mathias Agopian53331da2011-08-22 21:44:41 -07004057void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004058 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004059 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004060}
4061
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004062// Checks that the requested width and height are valid and updates them to the display dimensions
4063// if they are set to 0
4064static status_t updateDimensionsLocked(const sp<const DisplayDevice>& displayDevice,
4065 Transform::orientation_flags rotation,
4066 uint32_t* requestedWidth, uint32_t* requestedHeight) {
4067 // get screen geometry
4068 uint32_t displayWidth = displayDevice->getWidth();
4069 uint32_t displayHeight = displayDevice->getHeight();
Mathias Agopian9daa5c92010-10-12 16:05:48 -07004070
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004071 if (rotation & Transform::ROT_90) {
4072 std::swap(displayWidth, displayHeight);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004073 }
4074
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004075 if ((*requestedWidth > displayWidth) || (*requestedHeight > displayHeight)) {
4076 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4077 *requestedWidth, *requestedHeight, displayWidth, displayHeight);
4078 return BAD_VALUE;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004079 }
4080
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004081 if (*requestedWidth == 0) {
4082 *requestedWidth = displayWidth;
4083 }
4084 if (*requestedHeight == 0) {
4085 *requestedHeight = displayHeight;
4086 }
4087
4088 return NO_ERROR;
4089}
4090
4091// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4092class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004093public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004094 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4095 ~WindowDisconnector() {
4096 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004097 }
4098
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004099private:
4100 ANativeWindow* mWindow;
4101 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004102};
4103
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004104static status_t getWindowBuffer(ANativeWindow* window, uint32_t requestedWidth,
4105 uint32_t requestedHeight, bool hasWideColorDisplay,
4106 bool renderEngineUsesWideColor, ANativeWindowBuffer** outBuffer) {
4107 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4108 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4109
4110 int err = 0;
4111 err = native_window_set_buffers_dimensions(window, requestedWidth, requestedHeight);
4112 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
4113 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4114 err |= native_window_set_usage(window, usage);
4115
4116 if (hasWideColorDisplay) {
4117 err |= native_window_set_buffers_data_space(window,
4118 renderEngineUsesWideColor
4119 ? HAL_DATASPACE_DISPLAY_P3
4120 : HAL_DATASPACE_V0_SRGB);
4121 }
4122
4123 if (err != NO_ERROR) {
4124 return BAD_VALUE;
4125 }
4126
4127 /* TODO: Once we have the sync framework everywhere this can use
4128 * server-side waits on the fence that dequeueBuffer returns.
4129 */
4130 err = native_window_dequeue_buffer_and_wait(window, outBuffer);
4131 if (err != NO_ERROR) {
4132 return err;
4133 }
4134
4135 return NO_ERROR;
4136}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004137
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004138status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4139 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004140 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004141 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004142 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004143 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004144
4145 if (CC_UNLIKELY(display == 0))
4146 return BAD_VALUE;
4147
4148 if (CC_UNLIKELY(producer == 0))
4149 return BAD_VALUE;
4150
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004151 // if we have secure windows on this display, never allow the screen capture
4152 // unless the producer interface is local (i.e.: we can take a screenshot for
4153 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004154 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004155
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004156 // Convert to surfaceflinger's internal rotation type.
4157 Transform::orientation_flags rotationFlags;
4158 switch (rotation) {
4159 case ISurfaceComposer::eRotateNone:
4160 rotationFlags = Transform::ROT_0;
4161 break;
4162 case ISurfaceComposer::eRotate90:
4163 rotationFlags = Transform::ROT_90;
4164 break;
4165 case ISurfaceComposer::eRotate180:
4166 rotationFlags = Transform::ROT_180;
4167 break;
4168 case ISurfaceComposer::eRotate270:
4169 rotationFlags = Transform::ROT_270;
4170 break;
4171 default:
4172 rotationFlags = Transform::ROT_0;
4173 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
4174 break;
4175 }
4176
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004177 { // Autolock scope
4178 Mutex::Autolock lock(mStateLock);
4179 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
4180 updateDimensionsLocked(displayDevice, rotationFlags, &reqWidth, &reqHeight);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004181 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004182
4183 // create a surface (because we're a producer, and we need to
4184 // dequeue/queue a buffer)
4185 sp<Surface> surface = new Surface(producer, false);
4186
4187 // Put the screenshot Surface into async mode so that
4188 // Layer::headFenceHasSignaled will always return true and we'll latch the
4189 // first buffer regardless of whether or not its acquire fence has
4190 // signaled. This is needed to avoid a race condition in the rotation
4191 // animation. See b/30209608
4192 surface->setAsyncMode(true);
4193
4194 ANativeWindow* window = surface.get();
4195
4196 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4197 if (result != NO_ERROR) {
4198 return result;
4199 }
4200 WindowDisconnector disconnector(window, NATIVE_WINDOW_API_EGL);
4201
4202 ANativeWindowBuffer* buffer = nullptr;
4203 result = getWindowBuffer(window, reqWidth, reqHeight, hasWideColorDisplay,
4204 getRenderEngine().usesWideColor(), &buffer);
4205 if (result != NO_ERROR) {
4206 return result;
4207 }
4208
4209 // This mutex protects syncFd and captureResult for communication of the return values from the
4210 // main thread back to this Binder thread
4211 std::mutex captureMutex;
4212 std::condition_variable captureCondition;
4213 std::unique_lock<std::mutex> captureLock(captureMutex);
4214 int syncFd = -1;
4215 std::optional<status_t> captureResult;
4216
4217 sp<LambdaMessage> message = new LambdaMessage([&]() {
4218 // If there is a refresh pending, bug out early and tell the binder thread to try again
4219 // after the refresh.
4220 if (mRefreshPending) {
4221 ATRACE_NAME("Skipping screenshot for now");
4222 std::unique_lock<std::mutex> captureLock(captureMutex);
4223 captureResult = std::make_optional<status_t>(EAGAIN);
4224 captureCondition.notify_one();
4225 return;
4226 }
4227
4228 status_t result = NO_ERROR;
4229 int fd = -1;
4230 {
4231 Mutex::Autolock _l(mStateLock);
4232 sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4233 result = captureScreenImplLocked(device, buffer, sourceCrop, reqWidth, reqHeight,
4234 minLayerZ, maxLayerZ, useIdentityTransform,
4235 rotationFlags, isLocalScreenshot, &fd);
4236 }
4237
4238 {
4239 std::unique_lock<std::mutex> captureLock(captureMutex);
4240 syncFd = fd;
4241 captureResult = std::make_optional<status_t>(result);
4242 captureCondition.notify_one();
4243 }
4244 });
4245
4246 result = postMessageAsync(message);
4247 if (result == NO_ERROR) {
4248 captureCondition.wait(captureLock, [&]() { return captureResult; });
4249 while (*captureResult == EAGAIN) {
4250 captureResult.reset();
4251 result = postMessageAsync(message);
4252 if (result != NO_ERROR) {
4253 return result;
4254 }
4255 captureCondition.wait(captureLock, [&]() { return captureResult; });
4256 }
4257 result = *captureResult;
4258 }
4259
4260 if (result == NO_ERROR) {
4261 // queueBuffer takes ownership of syncFd
4262 result = window->queueBuffer(window, buffer, syncFd);
4263 }
4264
4265 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004266}
4267
Mathias Agopian180f10d2013-04-10 22:55:41 -07004268
4269void SurfaceFlinger::renderScreenImplLocked(
4270 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07004271 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004272 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004273 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07004274{
4275 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07004276 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004277
4278 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08004279 const int32_t hw_w = hw->getWidth();
4280 const int32_t hw_h = hw->getHeight();
4281 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07004282 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004283
Dan Stozac1879002014-05-22 15:59:05 -07004284 // if a default or invalid sourceCrop is passed in, set reasonable values
4285 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
4286 !sourceCrop.isValid()) {
4287 sourceCrop.setLeftTop(Point(0, 0));
4288 sourceCrop.setRightBottom(Point(hw_w, hw_h));
4289 }
4290
4291 // ensure that sourceCrop is inside screen
4292 if (sourceCrop.left < 0) {
4293 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4294 }
Dan Stozabe31f442014-06-11 11:20:54 -07004295 if (sourceCrop.right > hw_w) {
4296 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07004297 }
4298 if (sourceCrop.top < 0) {
4299 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4300 }
Dan Stozabe31f442014-06-11 11:20:54 -07004301 if (sourceCrop.bottom > hw_h) {
4302 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004303 }
4304
Romain Guy88d37dd2017-05-26 17:57:05 -07004305#ifdef USE_HWC2
4306 engine.setWideColor(hw->getWideColorSupport());
4307 engine.setColorMode(hw->getActiveColorMode());
4308#endif
4309
Mathias Agopian180f10d2013-04-10 22:55:41 -07004310 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004311 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004312
4313 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004314 engine.setViewportAndProjection(
4315 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004316 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004317
4318 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004319 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004320
Robert Carr1f0a16a2016-10-24 16:27:39 -07004321 // We loop through the first level of layers without traversing,
4322 // as we need to interpret min/max layer Z in the top level Z space.
4323 for (const auto& layer : mDrawingState.layersSortedByZ) {
4324 if (layer->getLayerStack() != hw->getLayerStack()) {
4325 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004326 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004327 const Layer::State& state(layer->getDrawingState());
4328 if (state.z < minLayerZ || state.z > maxLayerZ) {
4329 continue;
4330 }
Dan Stoza412903f2017-04-27 13:42:17 -07004331 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004332 if (!layer->isVisible()) {
4333 return;
4334 }
4335 if (filtering) layer->setFiltering(true);
4336 layer->draw(hw, useIdentityTransform);
4337 if (filtering) layer->setFiltering(false);
4338 });
4339 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004340
Mathias Agopian931bda12013-08-28 18:11:46 -07004341 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004342}
4343
Dan Stozaabcda352017-06-01 14:37:39 -07004344// A simple RAII class that holds an EGLImage and destroys it either:
4345// a) When the destroy() method is called
4346// b) When the object goes out of scope
4347class ImageHolder {
4348public:
4349 ImageHolder(EGLDisplay display, EGLImageKHR image) : mDisplay(display), mImage(image) {}
4350 ~ImageHolder() { destroy(); }
4351
4352 void destroy() {
4353 if (mImage != EGL_NO_IMAGE_KHR) {
4354 eglDestroyImageKHR(mDisplay, mImage);
4355 mImage = EGL_NO_IMAGE_KHR;
4356 }
4357 }
4358
4359private:
4360 const EGLDisplay mDisplay;
4361 EGLImageKHR mImage;
4362};
4363
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004364status_t SurfaceFlinger::captureScreenImplLocked(const sp<const DisplayDevice>& hw,
4365 ANativeWindowBuffer* buffer, Rect sourceCrop,
4366 uint32_t reqWidth, uint32_t reqHeight,
4367 int32_t minLayerZ, int32_t maxLayerZ,
4368 bool useIdentityTransform,
4369 Transform::orientation_flags rotation,
4370 bool isLocalScreenshot, int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004371 ATRACE_CALL();
4372
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004373 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004374 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004375 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004376 if ((layer->getLayerStack() != hw->getLayerStack()) ||
4377 (state.z < minLayerZ || state.z > maxLayerZ)) {
4378 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004379 }
Dan Stoza412903f2017-04-27 13:42:17 -07004380 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer *layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004381 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4382 layer->isSecure());
4383 });
4384 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004385
4386 if (!isLocalScreenshot && secureLayerIsVisible) {
4387 ALOGW("FB is protected: PERMISSION_DENIED");
4388 return PERMISSION_DENIED;
4389 }
4390
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004391 int syncFd = -1;
4392 // create an EGLImage from the buffer so we can later
4393 // turn it into a texture
4394 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4395 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4396 if (image == EGL_NO_IMAGE_KHR) {
4397 return BAD_VALUE;
4398 }
4399
Dan Stozaabcda352017-06-01 14:37:39 -07004400 // This will automatically destroy the image if we return before calling its destroy method
4401 ImageHolder imageHolder(mEGLDisplay, image);
4402
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004403 // this binds the given EGLImage as a framebuffer for the
4404 // duration of this scope.
4405 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
Dan Stozaabcda352017-06-01 14:37:39 -07004406 if (imageBond.getStatus() != NO_ERROR) {
4407 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004408 return INVALID_OPERATION;
4409 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004410
Dan Stozaabcda352017-06-01 14:37:39 -07004411 // this will in fact render into our dequeued buffer
4412 // via an FBO, which means we didn't have to create
4413 // an EGLSurface and therefore we're not
4414 // dependent on the context's EGLConfig.
4415 renderScreenImplLocked(
4416 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4417 useIdentityTransform, rotation);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004418
Dan Stozaabcda352017-06-01 14:37:39 -07004419 // Attempt to create a sync khr object that can produce a sync point. If that
4420 // isn't available, create a non-dupable sync object in the fallback path and
4421 // wait on it directly.
4422 EGLSyncKHR sync = EGL_NO_SYNC_KHR;
4423 if (!DEBUG_SCREENSHOTS) {
4424 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
4425 // native fence fd will not be populated until flush() is done.
4426 getRenderEngine().flush();
4427 }
4428
4429 if (sync != EGL_NO_SYNC_KHR) {
4430 // get the sync fd
4431 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4432 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4433 ALOGW("captureScreen: failed to dup sync khr object");
4434 syncFd = -1;
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004435 }
Dan Stozaabcda352017-06-01 14:37:39 -07004436 eglDestroySyncKHR(mEGLDisplay, sync);
4437 } else {
4438 // fallback path
4439 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004440 if (sync != EGL_NO_SYNC_KHR) {
Dan Stozaabcda352017-06-01 14:37:39 -07004441 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4442 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4443 EGLint eglErr = eglGetError();
4444 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4445 ALOGW("captureScreen: fence wait timed out");
4446 } else {
4447 ALOGW_IF(eglErr != EGL_SUCCESS,
4448 "captureScreen: error waiting on EGL fence: %#x", eglErr);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004449 }
4450 eglDestroySyncKHR(mEGLDisplay, sync);
4451 } else {
Dan Stozaabcda352017-06-01 14:37:39 -07004452 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004453 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004454 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004455 *outSyncFd = syncFd;
Dan Stozaabcda352017-06-01 14:37:39 -07004456
4457 if (DEBUG_SCREENSHOTS) {
4458 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4459 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4460 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4461 hw, minLayerZ, maxLayerZ);
4462 delete [] pixels;
4463 }
4464
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004465 // destroy our image
Dan Stozaabcda352017-06-01 14:37:39 -07004466 imageHolder.destroy();
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004467
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004468 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004469}
4470
Mathias Agopiand5556842013-09-19 17:08:37 -07004471void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004472 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004473 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004474 for (size_t y=0 ; y<h ; y++) {
4475 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4476 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004477 if (p[x] != 0xFF000000) return;
4478 }
4479 }
4480 ALOGE("*** we just took a black screenshot ***\n"
4481 "requested minz=%d, maxz=%d, layerStack=%d",
4482 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004483
Robert Carr2047fae2016-11-28 14:09:09 -08004484 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004485 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004486 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004487 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4488 state.z <= maxLayerZ) {
Dan Stoza412903f2017-04-27 13:42:17 -07004489 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004490 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4491 layer->isVisible() ? '+' : '-',
4492 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004493 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004494 i++;
4495 });
4496 }
4497 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004498 }
4499}
4500
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004501// ---------------------------------------------------------------------------
4502
Dan Stoza412903f2017-04-27 13:42:17 -07004503void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4504 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004505}
4506
Dan Stoza412903f2017-04-27 13:42:17 -07004507void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4508 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004509}
4510
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004511}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004512
4513
4514#if defined(__gl_h_)
4515#error "don't include gl/gl.h in this file"
4516#endif
4517
4518#if defined(__gl2_h_)
4519#error "don't include gl2/gl2.h in this file"
4520#endif