blob: a60c25d8909380ddf40e029422b3ab0ee9e1cb91 [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
Jiyong Park8d455e92017-08-10 20:30:56 +090099extern "C" EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
Mathias Agopianca088332013-03-28 17:44:13 -0700100
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800101namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700102
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800103
Jaesoo Lee43518572017-01-23 19:03:16 +0900104using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900105using namespace android::hardware::configstore::V1_0;
106
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800107// ---------------------------------------------------------------------------
108
Mathias Agopian99b49842011-06-27 16:05:52 -0700109const String16 sHardwareTest("android.permission.HARDWARE_TEST");
110const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
111const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
112const String16 sDump("android.permission.DUMP");
113
114// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800115int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
116int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700117bool SurfaceFlinger::useContextPriority;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700118int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700119bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800120uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800121bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800122bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800123int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600124bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700125
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800126SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700127 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800128 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700129 mTransactionPending(false),
130 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700131 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700132 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700133 mRepaintEverything(0),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800134 mHwc(nullptr),
135 mRealHwc(nullptr),
136 mVrHwc(nullptr),
137 mRenderEngine(nullptr),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800138 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800139 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800140 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800141 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800142 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800143 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700144 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700145 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700146 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700147 mDebugInSwapBuffers(0),
148 mLastSwapBufferTime(0),
149 mDebugInTransaction(0),
150 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700151 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700152 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800153 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000154 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700155 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700156 mHWVsyncAvailable(false),
Romain Guya9638732017-06-01 12:05:21 -0700157 mHasColorMatrix(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800158 mHasPoweredOff(false),
159 mFrameBuckets(),
160 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700161 mLastSwapTime(0),
Steven Thomas050b2c82017-03-06 11:45:16 -0800162 mNumLayers(0),
163 mVrFlingerRequestsDisplay(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800164{
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800165 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800166
167 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
168 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
169
170 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
171 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
172
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800173 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
174 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800175
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700176 useContextPriority = getBool< ISurfaceFlingerConfigs,
177 &ISurfaceFlingerConfigs::useContextPriority>(false);
178
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700179 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
180 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
181
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700182 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
183 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
184
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800185 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
186 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
187
Steven Thomas050b2c82017-03-06 11:45:16 -0800188 // Vr flinger is only enabled on Daydream ready devices.
189 useVrFlinger = getBool< ISurfaceFlingerConfigs,
190 &ISurfaceFlingerConfigs::useVrFlinger>(false);
191
Fabien Sanglard1971b632017-03-10 14:50:03 -0800192 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
193 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
194
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600195 hasWideColorDisplay =
196 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
197
Saurabh Shahce398e42017-07-13 10:45:07 -0700198 mPrimaryDispSync.init(hasSyncFramework, dispSyncPresentTimeOffset);
199
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800200 // debugging stuff...
201 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700202
Mathias Agopianb4b17302013-03-20 18:36:41 -0700203 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700204 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700205
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800206 property_get("debug.sf.showupdates", value, "0");
207 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700208
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700209 property_get("debug.sf.ddms", value, "0");
210 mDebugDDMS = atoi(value);
211 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700212 if (!startDdmConnection()) {
213 // start failed, and DDMS debugging not enabled
214 mDebugDDMS = 0;
215 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700216 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700217 ALOGI_IF(mDebugRegion, "showupdates enabled");
218 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700219
220 property_get("debug.sf.disable_backpressure", value, "0");
221 mPropagateBackpressure = !atoi(value);
222 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700223
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800224 property_get("debug.sf.enable_hwc_vds", value, "0");
225 mUseHwcVirtualDisplays = atoi(value);
226 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800227
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800228 property_get("ro.sf.disable_triple_buffer", value, "1");
229 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800230 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700231
Romain Guy11d63f42017-07-20 12:47:14 -0700232 // We should be reading 'persist.sys.sf.color_saturation' here
233 // but since /data may be encrypted, we need to wait until after vold
234 // comes online to attempt to read the property. The property is
235 // instead read after the boot animation
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800236}
237
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800238void SurfaceFlinger::onFirstRef()
239{
240 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800241}
242
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800243SurfaceFlinger::~SurfaceFlinger()
244{
Mathias Agopiana4912602012-07-12 14:25:33 -0700245 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
246 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
247 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800248}
249
Dan Stozac7014012014-02-14 15:03:43 -0800250void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800251{
252 // the window manager died on us. prepare its eulogy.
253
Andy McFadden13a082e2012-08-24 10:16:42 -0700254 // restore initial conditions (default device unblank, etc)
255 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800256
257 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700258 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800259}
260
Robert Carr1db73f62016-12-21 12:58:51 -0800261static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700262 status_t err = client->initCheck();
263 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800264 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800265 }
Robert Carr1db73f62016-12-21 12:58:51 -0800266 return nullptr;
267}
268
269sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
270 return initClient(new Client(this));
271}
272
273sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
274 const sp<IGraphicBufferProducer>& gbp) {
275 if (authenticateSurfaceTexture(gbp) == false) {
276 return nullptr;
277 }
278 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
279 if (layer == nullptr) {
280 return nullptr;
281 }
282
283 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800284}
285
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700286sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
287 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700288{
289 class DisplayToken : public BBinder {
290 sp<SurfaceFlinger> flinger;
291 virtual ~DisplayToken() {
292 // no more references, this display must be terminated
293 Mutex::Autolock _l(flinger->mStateLock);
294 flinger->mCurrentState.displays.removeItem(this);
295 flinger->setTransactionFlags(eDisplayTransactionNeeded);
296 }
297 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700298 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700299 : flinger(flinger) {
300 }
301 };
302
303 sp<BBinder> token = new DisplayToken(this);
304
305 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700306 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700307 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700308 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700309 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700310 return token;
311}
312
Jesse Hall6c913be2013-08-08 12:15:49 -0700313void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
314 Mutex::Autolock _l(mStateLock);
315
316 ssize_t idx = mCurrentState.displays.indexOfKey(display);
317 if (idx < 0) {
318 ALOGW("destroyDisplay: invalid display token");
319 return;
320 }
321
322 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
323 if (!info.isVirtualDisplay()) {
324 ALOGE("destroyDisplay called for non-virtual display");
325 return;
326 }
Irvelffc9efc2016-07-27 15:16:37 -0700327 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700328 mCurrentState.displays.removeItemsAt(idx);
329 setTransactionFlags(eDisplayTransactionNeeded);
330}
331
Jesse Hall692c7232012-11-08 15:41:56 -0800332void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800333 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800334 ALOGW_IF(mBuiltinDisplays[type],
335 "Overwriting display token for display type %d", type);
336 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800337 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700338 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800339 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700340 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800341}
342
Mathias Agopiane57f2922012-08-09 16:29:12 -0700343sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700344 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700345 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
346 return NULL;
347 }
Jesse Hall692c7232012-11-08 15:41:56 -0800348 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700349}
350
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800351void SurfaceFlinger::bootFinished()
352{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700353 if (mStartPropertySetThread->join() != NO_ERROR) {
354 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800355 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800356 const nsecs_t now = systemTime();
357 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000358 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700359
360 // wait patiently for the window manager death
361 const String16 name("window");
362 sp<IBinder> window(defaultServiceManager()->getService(name));
363 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700364 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700365 }
366
Steven Thomas050b2c82017-03-06 11:45:16 -0800367 if (mVrFlinger) {
368 mVrFlinger->OnBootFinished();
369 }
370
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700371 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700372 // formerly we would just kill the process, but we now ask it to exit so it
373 // can choose where to stop the animation.
374 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700375
376 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
377 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
378 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700379
Thierry Strudel2924d012017-08-14 15:19:37 -0700380 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700381 readPersistentProperties();
382 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700383 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800384}
385
Mathias Agopian3f844832013-08-07 21:24:32 -0700386void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700387 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700388 RenderEngine& engine;
389 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700390 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700391 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
392 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700393 }
394 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700395 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700396 return true;
397 }
398 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700399 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700400}
401
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700402class DispSyncSource : public VSyncSource, private DispSync::Callback {
403public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700404 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000405 const char* name) :
406 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700407 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700408 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000409 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
410 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700411 mDispSync(dispSync),
412 mCallbackMutex(),
413 mCallback(),
414 mVsyncMutex(),
415 mPhaseOffset(phaseOffset),
416 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700417
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700418 virtual ~DispSyncSource() {}
419
420 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700421 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700422 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000423 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700424 static_cast<DispSync::Callback*>(this));
425 if (err != NO_ERROR) {
426 ALOGE("error registering vsync callback: %s (%d)",
427 strerror(-err), err);
428 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700429 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700430 } else {
431 status_t err = mDispSync->removeEventListener(
432 static_cast<DispSync::Callback*>(this));
433 if (err != NO_ERROR) {
434 ALOGE("error unregistering vsync callback: %s (%d)",
435 strerror(-err), err);
436 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700437 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700438 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700439 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700440 }
441
442 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700443 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700444 mCallback = callback;
445 }
446
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700447 virtual void setPhaseOffset(nsecs_t phaseOffset) {
448 Mutex::Autolock lock(mVsyncMutex);
449
450 // Normalize phaseOffset to [0, period)
451 auto period = mDispSync->getPeriod();
452 phaseOffset %= period;
453 if (phaseOffset < 0) {
454 // If we're here, then phaseOffset is in (-period, 0). After this
455 // operation, it will be in (0, period)
456 phaseOffset += period;
457 }
458 mPhaseOffset = phaseOffset;
459
460 // If we're not enabled, we don't need to mess with the listeners
461 if (!mEnabled) {
462 return;
463 }
464
465 // Remove the listener with the old offset
466 status_t err = mDispSync->removeEventListener(
467 static_cast<DispSync::Callback*>(this));
468 if (err != NO_ERROR) {
469 ALOGE("error unregistering vsync callback: %s (%d)",
470 strerror(-err), err);
471 }
472
473 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000474 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700475 static_cast<DispSync::Callback*>(this));
476 if (err != NO_ERROR) {
477 ALOGE("error registering vsync callback: %s (%d)",
478 strerror(-err), err);
479 }
480 }
481
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700482private:
483 virtual void onDispSyncEvent(nsecs_t when) {
484 sp<VSyncSource::Callback> callback;
485 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700486 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700487 callback = mCallback;
488
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700489 if (mTraceVsync) {
490 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700491 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700492 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700493 }
494
495 if (callback != NULL) {
496 callback->onVSyncEvent(when);
497 }
498 }
499
Tim Murray4a4e4a22016-04-19 16:29:23 +0000500 const char* const mName;
501
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700502 int mValue;
503
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700504 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700505 const String8 mVsyncOnLabel;
506 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700507
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700508 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700509
510 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700511 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700512
513 Mutex mVsyncMutex; // Protects the following
514 nsecs_t mPhaseOffset;
515 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700516};
517
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700518class InjectVSyncSource : public VSyncSource {
519public:
520 InjectVSyncSource() {}
521
522 virtual ~InjectVSyncSource() {}
523
524 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
525 std::lock_guard<std::mutex> lock(mCallbackMutex);
526 mCallback = callback;
527 }
528
529 virtual void onInjectSyncEvent(nsecs_t when) {
530 std::lock_guard<std::mutex> lock(mCallbackMutex);
531 mCallback->onVSyncEvent(when);
532 }
533
534 virtual void setVSyncEnabled(bool) {}
535 virtual void setPhaseOffset(nsecs_t) {}
536
537private:
538 std::mutex mCallbackMutex; // Protects the following
539 sp<VSyncSource::Callback> mCallback;
540};
541
Wei Wangf9b05ee2017-07-19 20:59:39 -0700542// Do not call property_set on main thread which will be blocked by init
543// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700544void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700545 ALOGI( "SurfaceFlinger's main thread ready to run. "
546 "Initializing graphics H/W...");
547
Thierry Strudel2924d012017-08-14 15:19:37 -0700548 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900549
Dan Stoza9e56aa02015-11-02 13:00:03 -0800550 { // Autolock scope
551 Mutex::Autolock _l(mStateLock);
552
553 // initialize EGL for the default display
554 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
555 eglInitialize(mEGLDisplay, NULL, NULL);
556
557 // start the EventThread
558 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
559 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700560 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800561 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
562 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700563 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800564 mEventQueue.setEventThread(mSFEventThread);
565
Tim Murray22752852017-05-04 13:38:49 -0700566 // set EventThread and SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700567 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700568 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700569 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
570 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
571 }
Tim Murray22752852017-05-04 13:38:49 -0700572 if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
573 ALOGE("Couldn't set SCHED_FIFO for EventThread");
574 }
Tim Murray41a38532016-06-22 12:42:10 -0700575
Dan Stoza9e56aa02015-11-02 13:00:03 -0800576 // Get a RenderEngine for the given display / config (can't fail)
577 mRenderEngine = RenderEngine::create(mEGLDisplay,
Kalle Raitabbdcf1f2017-05-22 15:47:46 -0700578 HAL_PIXEL_FORMAT_RGBA_8888,
579 hasWideColorDisplay ? RenderEngine::WIDE_COLOR_SUPPORT : 0);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800580 }
581
582 // Drop the state lock while we initialize the hardware composer. We drop
583 // the lock because on creation, it will call back into SurfaceFlinger to
584 // initialize the primary display.
Steven Thomas050b2c82017-03-06 11:45:16 -0800585 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
586 "Starting with vr flinger active is not currently supported.");
Steven Thomas3cfac282017-02-06 12:29:30 -0800587 mRealHwc = new HWComposer(false);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800588 mHwc = mRealHwc;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800589 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
590
Jesse Hall692c7232012-11-08 15:41:56 -0800591 Mutex::Autolock _l(mStateLock);
592
Steven Thomas050b2c82017-03-06 11:45:16 -0800593 if (useVrFlinger) {
594 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700595 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
Steven Thomas050b2c82017-03-06 11:45:16 -0800596 mVrFlingerRequestsDisplay = requestDisplay;
597 signalTransaction();
598 };
599 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
600 vrFlingerRequestDisplayCallback);
601 if (!mVrFlinger) {
602 ALOGE("Failed to start vrflinger");
603 }
604 }
605
Mathias Agopian875d8e12013-06-07 15:35:48 -0700606 // retrieve the EGL context that was selected/created
607 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700608
Mathias Agopianda27af92012-09-13 18:17:13 -0700609 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
610 "couldn't create EGLContext");
611
Dan Stoza9e56aa02015-11-02 13:00:03 -0800612 // make the GLContext current so that we can create textures when creating
613 // Layers (which may happens before we render something)
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700614 getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext);
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700615
Jamie Gennisd1700752013-10-14 12:22:52 -0700616 mEventControlThread = new EventControlThread(this);
617 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
618
Mathias Agopian92a979a2012-08-02 18:32:23 -0700619 // initialize our drawing state
620 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700621
Andy McFadden13a082e2012-08-24 10:16:42 -0700622 // set initial conditions (e.g. unblank default device)
623 initializeDisplays();
624
Dan Stoza4e637772016-07-28 13:31:51 -0700625 mRenderEngine->primeCache();
626
Wei Wangf9b05ee2017-07-19 20:59:39 -0700627 // Inform native graphics APIs whether the present timestamp is supported:
628 if (getHwComposer().hasCapability(
629 HWC2::Capability::PresentFenceIsNotReliable)) {
630 mStartPropertySetThread = new StartPropertySetThread(false);
631 } else {
632 mStartPropertySetThread = new StartPropertySetThread(true);
633 }
634
635 if (mStartPropertySetThread->Start() != NO_ERROR) {
636 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800637 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800638
Dan Stoza9e56aa02015-11-02 13:00:03 -0800639 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700640}
641
Romain Guy11d63f42017-07-20 12:47:14 -0700642void SurfaceFlinger::readPersistentProperties() {
643 char value[PROPERTY_VALUE_MAX];
644
645 property_get("persist.sys.sf.color_saturation", value, "1.0");
646 mSaturation = atof(value);
647 ALOGV("Saturation is set to %.2f", mSaturation);
648}
649
Mathias Agopiana67e4182012-06-19 17:26:12 -0700650void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800651 // Start boot animation service by setting a property mailbox
652 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700653 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800654 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700655 if (mStartPropertySetThread->join() != NO_ERROR) {
656 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800657 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700658}
659
Mathias Agopian875d8e12013-06-07 15:35:48 -0700660size_t SurfaceFlinger::getMaxTextureSize() const {
661 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700662}
663
Mathias Agopian875d8e12013-06-07 15:35:48 -0700664size_t SurfaceFlinger::getMaxViewportDims() const {
665 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700666}
667
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800668// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800669
Jamie Gennis582270d2011-08-17 18:19:00 -0700670bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800671 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800672 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800673 return authenticateSurfaceTextureLocked(bufferProducer);
674}
675
676bool SurfaceFlinger::authenticateSurfaceTextureLocked(
677 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800678 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700679 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800680}
681
Brian Anderson6b376712017-04-04 10:51:39 -0700682status_t SurfaceFlinger::getSupportedFrameTimestamps(
683 std::vector<FrameEvent>* outSupported) const {
684 *outSupported = {
685 FrameEvent::REQUESTED_PRESENT,
686 FrameEvent::ACQUIRE,
687 FrameEvent::LATCH,
688 FrameEvent::FIRST_REFRESH_START,
689 FrameEvent::LAST_REFRESH_START,
690 FrameEvent::GPU_COMPOSITION_DONE,
691 FrameEvent::DEQUEUE_READY,
692 FrameEvent::RELEASE,
693 };
694 if (!getHwComposer().hasCapability(
695 HWC2::Capability::PresentFenceIsNotReliable)) {
696 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
697 }
698 return NO_ERROR;
699}
700
Dan Stoza7f7da322014-05-02 15:26:25 -0700701status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
702 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700703 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700704 return BAD_VALUE;
705 }
706
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500707 if (!display.get())
708 return NAME_NOT_FOUND;
709
Jesse Hall692c7232012-11-08 15:41:56 -0800710 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700711 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800712 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700713 type = i;
714 break;
715 }
716 }
717
718 if (type < 0) {
719 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700720 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700721
Mathias Agopian8b736f12012-08-13 17:54:26 -0700722 // TODO: Not sure if display density should handled by SF any longer
723 class Density {
724 static int getDensityFromProperty(char const* propName) {
725 char property[PROPERTY_VALUE_MAX];
726 int density = 0;
727 if (property_get(propName, property, NULL) > 0) {
728 density = atoi(property);
729 }
730 return density;
731 }
732 public:
733 static int getEmuDensity() {
734 return getDensityFromProperty("qemu.sf.lcd_density"); }
735 static int getBuildDensity() {
736 return getDensityFromProperty("ro.sf.lcd_density"); }
737 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700738
Dan Stoza7f7da322014-05-02 15:26:25 -0700739 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700740
Dan Stoza9e56aa02015-11-02 13:00:03 -0800741 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700742 DisplayInfo info = DisplayInfo();
743
Dan Stoza9e56aa02015-11-02 13:00:03 -0800744 float xdpi = hwConfig->getDpiX();
745 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700746
747 if (type == DisplayDevice::DISPLAY_PRIMARY) {
748 // The density of the device is provided by a build property
749 float density = Density::getBuildDensity() / 160.0f;
750 if (density == 0) {
751 // the build doesn't provide a density -- this is wrong!
752 // use xdpi instead
753 ALOGE("ro.sf.lcd_density must be defined as a build property");
754 density = xdpi / 160.0f;
755 }
756 if (Density::getEmuDensity()) {
757 // if "qemu.sf.lcd_density" is specified, it overrides everything
758 xdpi = ydpi = density = Density::getEmuDensity();
759 density /= 160.0f;
760 }
761 info.density = density;
762
763 // TODO: this needs to go away (currently needed only by webkit)
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000764 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
765 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700766 } else {
767 // TODO: where should this value come from?
768 static const int TV_DENSITY = 213;
769 info.density = TV_DENSITY / 160.0f;
770 info.orientation = 0;
771 }
772
Dan Stoza9e56aa02015-11-02 13:00:03 -0800773 info.w = hwConfig->getWidth();
774 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700775 info.xdpi = xdpi;
776 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800777 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900778 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800779
Andy McFadden91b2ca82014-06-13 14:04:23 -0700780 // This is how far in advance a buffer must be queued for
781 // presentation at a given time. If you want a buffer to appear
782 // on the screen at time N, you must submit the buffer before
783 // (N - presentationDeadline).
784 //
785 // Normally it's one full refresh period (to give SF a chance to
786 // latch the buffer), but this can be reduced by configuring a
787 // DispSync offset. Any additional delays introduced by the hardware
788 // composer or panel must be accounted for here.
789 //
790 // We add an additional 1ms to allow for processing time and
791 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800792 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800793 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700794
795 // All non-virtual displays are currently considered secure.
796 info.secure = true;
797
Michael Wright28f24d02016-07-12 13:30:53 -0700798 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700799 }
800
Dan Stoza7f7da322014-05-02 15:26:25 -0700801 return NO_ERROR;
802}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700803
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800804status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700805 DisplayStatInfo* stats) {
806 if (stats == NULL) {
807 return BAD_VALUE;
808 }
809
810 // FIXME for now we always return stats for the primary display
811 memset(stats, 0, sizeof(*stats));
812 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
813 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
814 return NO_ERROR;
815}
816
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700817int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800818 if (display == NULL) {
819 ALOGE("%s : display is NULL", __func__);
820 return BAD_VALUE;
821 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700822
823 sp<const DisplayDevice> device(getDisplayDevice(display));
Dan Stoza24a42e92015-03-09 10:04:11 -0700824 if (device != NULL) {
825 return device->getActiveConfig();
826 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700827
Dan Stoza24a42e92015-03-09 10:04:11 -0700828 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700829}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700830
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700831void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
832 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
833 this);
834 int32_t type = hw->getDisplayType();
835 int currentMode = hw->getActiveConfig();
836
837 if (mode == currentMode) {
838 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
839 return;
840 }
841
842 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
843 ALOGW("Trying to set config for virtual display");
844 return;
845 }
846
847 hw->setActiveConfig(mode);
848 getHwComposer().setActiveConfig(type, mode);
849}
850
851status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
852 class MessageSetActiveConfig: public MessageBase {
853 SurfaceFlinger& mFlinger;
854 sp<IBinder> mDisplay;
855 int mMode;
856 public:
857 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
858 int mode) :
859 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
860 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700861 Vector<DisplayInfo> configs;
862 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700863 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700864 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700865 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700866 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700867 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700868 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
869 if (hw == NULL) {
870 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700871 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700872 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
873 ALOGW("Attempt to set active config = %d for virtual display",
874 mMode);
875 } else {
876 mFlinger.setActiveConfigInternal(hw, mMode);
877 }
878 return true;
879 }
880 };
881 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
882 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700883 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700884}
Michael Wright28f24d02016-07-12 13:30:53 -0700885status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
886 Vector<android_color_mode_t>* outColorModes) {
887 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
888 return BAD_VALUE;
889 }
890
891 if (!display.get()) {
892 return NAME_NOT_FOUND;
893 }
894
895 int32_t type = NAME_NOT_FOUND;
896 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
897 if (display == mBuiltinDisplays[i]) {
898 type = i;
899 break;
900 }
901 }
902
903 if (type < 0) {
904 return type;
905 }
906
907 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
908 outColorModes->clear();
909 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
910
911 return NO_ERROR;
912}
913
914android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700915 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700916 if (device != nullptr) {
917 return device->getActiveColorMode();
918 }
919 return static_cast<android_color_mode_t>(BAD_VALUE);
920}
921
922void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
923 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700924 int32_t type = hw->getDisplayType();
925 android_color_mode_t currentMode = hw->getActiveColorMode();
926
927 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700928 return;
929 }
930
931 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
932 ALOGW("Trying to set config for virtual display");
933 return;
934 }
935
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600936 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
937 hw->getDisplayType());
938
Michael Wright28f24d02016-07-12 13:30:53 -0700939 hw->setActiveColorMode(mode);
940 getHwComposer().setActiveColorMode(type, mode);
941}
942
943
944status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
945 android_color_mode_t colorMode) {
946 class MessageSetActiveColorMode: public MessageBase {
947 SurfaceFlinger& mFlinger;
948 sp<IBinder> mDisplay;
949 android_color_mode_t mMode;
950 public:
951 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
952 android_color_mode_t mode) :
953 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
954 virtual bool handler() {
955 Vector<android_color_mode_t> modes;
956 mFlinger.getDisplayColorModes(mDisplay, &modes);
957 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
958 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600959 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
960 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700961 return true;
962 }
963 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
964 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600965 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
966 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700967 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600968 ALOGW("Attempt to set active color mode %s %d for virtual display",
969 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -0700970 } else {
971 mFlinger.setActiveColorModeInternal(hw, mMode);
972 }
973 return true;
974 }
975 };
976 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
977 postMessageSync(msg);
978 return NO_ERROR;
979}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700980
Svetoslavd85084b2014-03-20 10:28:31 -0700981status_t SurfaceFlinger::clearAnimationFrameStats() {
982 Mutex::Autolock _l(mStateLock);
983 mAnimFrameTracker.clearStats();
984 return NO_ERROR;
985}
986
987status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
988 Mutex::Autolock _l(mStateLock);
989 mAnimFrameTracker.getStats(outStats);
990 return NO_ERROR;
991}
992
Dan Stozac4f471e2016-03-24 09:31:08 -0700993status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
994 HdrCapabilities* outCapabilities) const {
995 Mutex::Autolock _l(mStateLock);
996
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700997 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -0700998 if (displayDevice == nullptr) {
999 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1000 return BAD_VALUE;
1001 }
1002
1003 std::unique_ptr<HdrCapabilities> capabilities =
1004 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
1005 if (capabilities) {
1006 std::swap(*outCapabilities, *capabilities);
1007 } else {
1008 return BAD_VALUE;
1009 }
1010
1011 return NO_ERROR;
1012}
1013
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001014status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
1015 if (enable == mInjectVSyncs) {
1016 return NO_ERROR;
1017 }
1018
1019 if (enable) {
1020 mInjectVSyncs = enable;
1021 ALOGV("VSync Injections enabled");
1022 if (mVSyncInjector.get() == nullptr) {
1023 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -07001024 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001025 }
1026 mEventQueue.setEventThread(mInjectorEventThread);
1027 } else {
1028 mInjectVSyncs = enable;
1029 ALOGV("VSync Injections disabled");
1030 mEventQueue.setEventThread(mSFEventThread);
1031 mVSyncInjector.clear();
1032 }
1033 return NO_ERROR;
1034}
1035
1036status_t SurfaceFlinger::injectVSync(nsecs_t when) {
1037 if (!mInjectVSyncs) {
1038 ALOGE("VSync Injections not enabled");
1039 return BAD_VALUE;
1040 }
1041 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1042 ALOGV("Injecting VSync inside SurfaceFlinger");
1043 mVSyncInjector->onInjectSyncEvent(when);
1044 }
1045 return NO_ERROR;
1046}
1047
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001048// ----------------------------------------------------------------------------
1049
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001050sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1051 ISurfaceComposer::VsyncSource vsyncSource) {
1052 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1053 return mSFEventThread->createEventConnection();
1054 } else {
1055 return mEventThread->createEventConnection();
1056 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001057}
1058
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001059// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001060
1061void SurfaceFlinger::waitForEvent() {
1062 mEventQueue.waitMessage();
1063}
1064
1065void SurfaceFlinger::signalTransaction() {
1066 mEventQueue.invalidate();
1067}
1068
1069void SurfaceFlinger::signalLayerUpdate() {
1070 mEventQueue.invalidate();
1071}
1072
1073void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001074 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001075 mEventQueue.refresh();
1076}
1077
1078status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001079 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001080 return mEventQueue.postMessage(msg, reltime);
1081}
1082
1083status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001084 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001085 status_t res = mEventQueue.postMessage(msg, reltime);
1086 if (res == NO_ERROR) {
1087 msg->wait();
1088 }
1089 return res;
1090}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001091
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001092void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001093 do {
1094 waitForEvent();
1095 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001096}
1097
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001098void SurfaceFlinger::enableHardwareVsync() {
1099 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001100 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001101 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001102 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1103 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001104 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001105 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001106}
1107
Jesse Hall948fe0c2013-10-14 12:56:09 -07001108void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001109 Mutex::Autolock _l(mHWVsyncLock);
1110
Jesse Hall948fe0c2013-10-14 12:56:09 -07001111 if (makeAvailable) {
1112 mHWVsyncAvailable = true;
1113 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001114 // Hardware vsync is not currently available, so abort the resync
1115 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001116 return;
1117 }
1118
Dan Stoza9e56aa02015-11-02 13:00:03 -08001119 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1120 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001121
1122 mPrimaryDispSync.reset();
1123 mPrimaryDispSync.setPeriod(period);
1124
1125 if (!mPrimaryHWVsyncEnabled) {
1126 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001127 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1128 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001129 mPrimaryHWVsyncEnabled = true;
1130 }
1131}
1132
Jesse Hall948fe0c2013-10-14 12:56:09 -07001133void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001134 Mutex::Autolock _l(mHWVsyncLock);
1135 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001136 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1137 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001138 mPrimaryDispSync.endResync();
1139 mPrimaryHWVsyncEnabled = false;
1140 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001141 if (makeUnavailable) {
1142 mHWVsyncAvailable = false;
1143 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001144}
1145
Tim Murray4a4e4a22016-04-19 16:29:23 +00001146void SurfaceFlinger::resyncWithRateLimit() {
1147 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001148
1149 // No explicit locking is needed here since EventThread holds a lock while calling this method
1150 static nsecs_t sLastResyncAttempted = 0;
1151 const nsecs_t now = systemTime();
1152 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001153 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001154 }
Dan Stoza57164302017-05-08 14:03:54 -07001155 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001156}
1157
Steven Thomas3cfac282017-02-06 12:29:30 -08001158void SurfaceFlinger::onVSyncReceived(HWComposer* composer, int32_t type,
1159 nsecs_t timestamp) {
1160 Mutex::Autolock lock(mStateLock);
1161 // Ignore any vsyncs from the non-active hardware composer.
1162 if (composer != mHwc) {
1163 return;
1164 }
1165
Jamie Gennisd1700752013-10-14 12:22:52 -07001166 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001167
Jamie Gennisd1700752013-10-14 12:22:52 -07001168 { // Scope for the lock
1169 Mutex::Autolock _l(mHWVsyncLock);
1170 if (type == 0 && mPrimaryHWVsyncEnabled) {
1171 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001172 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001173 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001174
1175 if (needsHwVsync) {
1176 enableHardwareVsync();
1177 } else {
1178 disableHardwareVsync(false);
1179 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001180}
1181
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001182void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001183 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001184 *compositorTiming = mCompositorTiming;
1185}
1186
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001187void SurfaceFlinger::createDefaultDisplayDevice() {
1188 const int32_t type = DisplayDevice::DISPLAY_PRIMARY;
1189 wp<IBinder> token = mBuiltinDisplays[type];
1190
1191 // All non-virtual displays are currently considered secure.
1192 const bool isSecure = true;
1193
1194 sp<IGraphicBufferProducer> producer;
1195 sp<IGraphicBufferConsumer> consumer;
1196 BufferQueue::createBufferQueue(&producer, &consumer);
1197
1198 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1199
1200 bool hasWideColorModes = false;
1201 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1202 for (android_color_mode_t colorMode : modes) {
1203 switch (colorMode) {
1204 case HAL_COLOR_MODE_DISPLAY_P3:
1205 case HAL_COLOR_MODE_ADOBE_RGB:
1206 case HAL_COLOR_MODE_DCI_P3:
1207 hasWideColorModes = true;
1208 break;
1209 default:
1210 break;
1211 }
1212 }
1213 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
1214 token, fbs, producer, mRenderEngine->getEGLConfig(),
1215 hasWideColorModes && hasWideColorDisplay);
1216 mDisplays.add(token, hw);
Thierry Strudel2924d012017-08-14 15:19:37 -07001217 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
1218 if (hasWideColorModes && hasWideColorDisplay) {
1219 defaultColorMode = HAL_COLOR_MODE_SRGB;
1220 }
1221 setActiveColorModeInternal(hw, defaultColorMode);
Courtney Goeltzenleuchter281e8112017-07-13 17:54:01 -06001222 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001223}
1224
1225void SurfaceFlinger::onHotplugReceived(HWComposer* composer, int32_t disp, bool connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001226 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001227
1228 if (composer->isUsingVrComposer()) {
1229 // We handle initializing the primary display device for the VR
1230 // window manager hwc explicitly at the time of transition.
1231 if (disp != DisplayDevice::DISPLAY_PRIMARY) {
1232 ALOGE("External displays are not supported by the vr hardware composer.");
1233 }
1234 return;
1235 }
1236
Dan Stoza9e56aa02015-11-02 13:00:03 -08001237 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1238 Mutex::Autolock lock(mStateLock);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001239 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1240 createDefaultDisplayDevice();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001241 } else {
1242 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001243 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001244 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001245 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001246 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001247 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1248 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001249 }
1250 setTransactionFlags(eDisplayTransactionNeeded);
1251
Andy McFadden9e9689c2012-10-10 18:17:51 -07001252 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001253 }
Mathias Agopian86303202012-07-24 22:46:10 -07001254}
1255
Steven Thomas3cfac282017-02-06 12:29:30 -08001256void SurfaceFlinger::onInvalidateReceived(HWComposer* composer) {
1257 Mutex::Autolock lock(mStateLock);
1258 if (composer == mHwc) {
1259 repaintEverything();
1260 } else {
1261 // This isn't from our current hardware composer. If it's a callback
1262 // from the real composer, forward the refresh request to vr
1263 // flinger. Otherwise ignore it.
1264 if (!composer->isUsingVrComposer()) {
1265 mVrFlinger->OnHardwareComposerRefresh();
1266 }
1267 }
1268}
1269
Dan Stoza9e56aa02015-11-02 13:00:03 -08001270void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001271 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001272 getHwComposer().setVsyncEnabled(disp,
1273 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001274}
1275
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001276// Note: it is assumed the caller holds |mStateLock| when this is called
1277void SurfaceFlinger::resetHwcLocked() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001278 disableHardwareVsync(true);
1279 clearHwcLayers(mDrawingState.layersSortedByZ);
1280 clearHwcLayers(mCurrentState.layersSortedByZ);
Steven Thomasf5a5f6e2017-07-17 13:59:23 -07001281 for (size_t disp = 0; disp < mDisplays.size(); ++disp) {
1282 clearHwcLayers(mDisplays[disp]->getVisibleLayersSortedByZ());
1283 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001284 // Clear the drawing state so that the logic inside of
1285 // handleTransactionLocked will fire. It will determine the delta between
1286 // mCurrentState and mDrawingState and re-apply all changes when we make the
1287 // transition.
1288 mDrawingState.displays.clear();
Alex Sakhartchoukda8490d2017-04-12 17:09:42 -04001289 // Release virtual display hwcId during vr mode transition.
1290 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1291 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1292 if (displayDevice->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL) {
1293 displayDevice->disconnect(getHwComposer());
1294 }
1295 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001296 mDisplays.clear();
1297}
1298
Steven Thomas050b2c82017-03-06 11:45:16 -08001299void SurfaceFlinger::updateVrFlinger() {
1300 if (!mVrFlinger)
1301 return;
1302 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1303 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001304 return;
1305 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001306
Steven Thomas050b2c82017-03-06 11:45:16 -08001307 if (vrFlingerRequestsDisplay && !mVrHwc) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001308 // Construct new HWComposer without holding any locks.
1309 mVrHwc = new HWComposer(true);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001310
1311 // Set up the event handlers. This step is neccessary to initialize the internal state of
1312 // the hardware composer object properly. Our callbacks are designed such that if they are
1313 // triggered between now and the point where the display is properly re-initialized, they
1314 // will not have any effect, so this is safe to do here, before the lock is aquired.
1315 mVrHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
Mark Urbanus209beca2017-02-23 11:16:04 -08001316 ALOGV("Vr HWC created");
1317 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001318
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001319 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001320
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001321 if (vrFlingerRequestsDisplay) {
1322 resetHwcLocked();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001323
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001324 mHwc = mVrHwc;
1325 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001326
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001327 } else {
1328 mVrFlinger->SeizeDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001329
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001330 resetHwcLocked();
1331
1332 mHwc = mRealHwc;
1333 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001334 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001335
1336 mVisibleRegionsDirty = true;
1337 invalidateHwcGeometry();
1338
1339 // Explicitly re-initialize the primary display. This is because some other
1340 // parts of this class rely on the primary display always being available.
1341 createDefaultDisplayDevice();
1342
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001343 // Re-enable default display.
1344 sp<LambdaMessage> requestMessage = new LambdaMessage([&]() {
1345 sp<DisplayDevice> hw(getDisplayDevice(mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1346 setPowerModeInternal(hw, HWC_POWER_MODE_NORMAL);
1347
1348 // Reset the timing values to account for the period of the swapped in HWC
1349 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1350 const nsecs_t period = activeConfig->getVsyncPeriod();
1351 mAnimFrameTracker.setDisplayRefreshPeriod(period);
1352
1353 // Use phase of 0 since phase is not known.
1354 // Use latency of 0, which will snap to the ideal latency.
1355 setCompositorTimingSnapped(0, period, 0);
1356 });
1357 postMessageAsync(requestMessage);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001358
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001359 android_atomic_or(1, &mRepaintEverything);
1360 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001361}
1362
Mathias Agopian4fec8732012-06-29 14:12:52 -07001363void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001364 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001365 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001366 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001367 bool frameMissed = !mHadClientComposition &&
1368 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001369 (mPreviousPresentFence->getSignalTime() ==
1370 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001371 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001372 if (mPropagateBackpressure && frameMissed) {
Fabien Sanglardaf5b6b82017-02-23 11:17:11 -08001373 ALOGD("Backpressure trigger, skipping transaction & refresh!");
Dan Stoza50182882016-07-08 12:02:20 -07001374 signalLayerUpdate();
1375 break;
1376 }
1377
Steven Thomas050b2c82017-03-06 11:45:16 -08001378 // Now that we're going to make it to the handleMessageTransaction()
1379 // call below it's safe to call updateVrFlinger(), which will
1380 // potentially trigger a display handoff.
1381 updateVrFlinger();
1382
Dan Stoza6b9454d2014-11-07 16:00:59 -08001383 bool refreshNeeded = handleMessageTransaction();
1384 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001385 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001386 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001387 // Signal a refresh if a transaction modified the window state,
1388 // a new buffer was latched, or if HWC has requested a full
1389 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001390 signalRefresh();
1391 }
1392 break;
1393 }
1394 case MessageQueue::REFRESH: {
1395 handleMessageRefresh();
1396 break;
1397 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001398 }
1399}
1400
Dan Stoza6b9454d2014-11-07 16:00:59 -08001401bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001402 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001403 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001404 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001405 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001406 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001407 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001408}
1409
Dan Stoza6b9454d2014-11-07 16:00:59 -08001410bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001411 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001412 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001413}
1414
1415void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001416 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001417
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001418 mRefreshPending = false;
1419
Pablo Ceballos40845df2016-01-25 17:41:15 -08001420 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001421
Brian Andersond6927fb2016-07-23 23:37:30 -07001422 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001423 rebuildLayerStacks();
1424 setUpHWComposer();
1425 doDebugFlashRegions();
1426 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001427 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001428
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001429 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001430
1431 mHadClientComposition = false;
1432 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1433 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1434 mHadClientComposition = mHadClientComposition ||
1435 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1436 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001437
Dan Stoza9e56aa02015-11-02 13:00:03 -08001438 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001439}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001440
Mathias Agopiancd60f992012-08-16 16:28:27 -07001441void SurfaceFlinger::doDebugFlashRegions()
1442{
1443 // is debugging enabled
1444 if (CC_LIKELY(!mDebugRegion))
1445 return;
1446
1447 const bool repaintEverything = mRepaintEverything;
1448 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1449 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001450 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001451 // transform the dirty region into this screen's coordinate space
1452 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1453 if (!dirtyRegion.isEmpty()) {
1454 // redraw the whole screen
1455 doComposeSurfaces(hw, Region(hw->bounds()));
1456
1457 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001458 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001459 RenderEngine& engine(getRenderEngine());
1460 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1461
Mathias Agopianda27af92012-09-13 18:17:13 -07001462 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001463 }
1464 }
1465 }
1466
1467 postFramebuffer();
1468
1469 if (mDebugRegion > 1) {
1470 usleep(mDebugRegion * 1000);
1471 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001472
Dan Stoza9e56aa02015-11-02 13:00:03 -08001473 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001474 auto& displayDevice = mDisplays[displayId];
1475 if (!displayDevice->isDisplayOn()) {
1476 continue;
1477 }
1478
1479 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001480 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1481 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001482 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001483}
1484
Brian Andersond6927fb2016-07-23 23:37:30 -07001485void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001486{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001487 ATRACE_CALL();
1488 ALOGV("preComposition");
1489
Mathias Agopiancd60f992012-08-16 16:28:27 -07001490 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001491 mDrawingState.traverseInZOrder([&](Layer* layer) {
1492 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001493 needExtraInvalidate = true;
1494 }
Robert Carr2047fae2016-11-28 14:09:09 -08001495 });
1496
Mathias Agopiancd60f992012-08-16 16:28:27 -07001497 if (needExtraInvalidate) {
1498 signalLayerUpdate();
1499 }
1500}
1501
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001502void SurfaceFlinger::updateCompositorTiming(
1503 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1504 std::shared_ptr<FenceTime>& presentFenceTime) {
1505 // Update queue of past composite+present times and determine the
1506 // most recently known composite to present latency.
1507 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1508 nsecs_t compositeToPresentLatency = -1;
1509 while (!mCompositePresentTimes.empty()) {
1510 CompositePresentTime& cpt = mCompositePresentTimes.front();
1511 // Cached values should have been updated before calling this method,
1512 // which helps avoid duplicate syscalls.
1513 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1514 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1515 break;
1516 }
1517 compositeToPresentLatency = displayTime - cpt.composite;
1518 mCompositePresentTimes.pop();
1519 }
1520
1521 // Don't let mCompositePresentTimes grow unbounded, just in case.
1522 while (mCompositePresentTimes.size() > 16) {
1523 mCompositePresentTimes.pop();
1524 }
1525
Brian Andersond0010582017-03-07 13:20:31 -08001526 setCompositorTimingSnapped(
1527 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1528}
1529
1530void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1531 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001532 // Integer division and modulo round toward 0 not -inf, so we need to
1533 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001534 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001535 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1536 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1537
Brian Andersond0010582017-03-07 13:20:31 -08001538 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1539 if (idealLatency <= 0) {
1540 idealLatency = vsyncInterval;
1541 }
1542
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001543 // Snap the latency to a value that removes scheduling jitter from the
1544 // composition and present times, which often have >1ms of jitter.
1545 // Reducing jitter is important if an app attempts to extrapolate
1546 // something (such as user input) to an accurate diasplay time.
1547 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1548 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001549 nsecs_t bias = vsyncInterval / 2;
1550 int64_t extraVsyncs =
1551 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1552 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1553 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001554
Brian Andersond0010582017-03-07 13:20:31 -08001555 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001556 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1557 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001558 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001559}
1560
1561void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001562{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001563 ATRACE_CALL();
1564 ALOGV("postComposition");
1565
Brian Anderson3546a3f2016-07-14 11:51:14 -07001566 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001567 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001568 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001569 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001570 }
1571
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001572 // |mStateLock| not needed as we are on the main thread
1573 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001574
1575 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1576 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1577 glCompositionDoneFenceTime =
1578 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1579 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1580 } else {
1581 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1582 }
1583 mGlCompositionDoneTimeline.updateSignalTimes();
1584
Brian Anderson4e606e32017-03-16 15:34:57 -07001585 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1586 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1587 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001588 mDisplayTimeline.updateSignalTimes();
1589
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001590 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1591 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1592
1593 // We use the refreshStartTime which might be sampled a little later than
1594 // when we started doing work for this frame, but that should be okay
1595 // since updateCompositorTiming has snapping logic.
1596 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001597 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001598 CompositorTiming compositorTiming;
1599 {
1600 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1601 compositorTiming = mCompositorTiming;
1602 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001603
Robert Carr2047fae2016-11-28 14:09:09 -08001604 mDrawingState.traverseInZOrder([&](Layer* layer) {
1605 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001606 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001607 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001608 recordBufferingStats(layer->getName().string(),
1609 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001610 }
Robert Carr2047fae2016-11-28 14:09:09 -08001611 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001612
Brian Anderson4e606e32017-03-16 15:34:57 -07001613 if (presentFence->isValid()) {
1614 if (mPrimaryDispSync.addPresentFence(presentFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001615 enableHardwareVsync();
1616 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001617 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001618 }
1619 }
1620
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001621 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001622 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001623 enableHardwareVsync();
1624 }
1625 }
1626
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001627 if (mAnimCompositionPending) {
1628 mAnimCompositionPending = false;
1629
Brian Anderson4e606e32017-03-16 15:34:57 -07001630 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001631 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001632 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001633 } else {
1634 // The HWC doesn't support present fences, so use the refresh
1635 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001636 nsecs_t presentTime =
1637 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001638 mAnimFrameTracker.setActualPresentTime(presentTime);
1639 }
1640 mAnimFrameTracker.advanceFrame();
1641 }
Dan Stozab90cf072015-03-05 11:05:59 -08001642
1643 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1644 return;
1645 }
1646
1647 nsecs_t currentTime = systemTime();
1648 if (mHasPoweredOff) {
1649 mHasPoweredOff = false;
1650 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001651 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001652 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001653 if (numPeriods < NUM_BUCKETS - 1) {
1654 mFrameBuckets[numPeriods] += elapsedTime;
1655 } else {
1656 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1657 }
1658 mTotalTime += elapsedTime;
1659 }
1660 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001661}
1662
1663void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001664 ATRACE_CALL();
1665 ALOGV("rebuildLayerStacks");
1666
Mathias Agopiancd60f992012-08-16 16:28:27 -07001667 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001668 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1669 ATRACE_CALL();
1670 mVisibleRegionsDirty = false;
1671 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001672
Jeff Sharkey76488112017-02-27 14:15:18 -07001673 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1674 Region opaqueRegion;
1675 Region dirtyRegion;
1676 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wuf9fc8ee2017-11-16 11:45:52 -08001677 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001678 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1679 const Transform& tr(displayDevice->getTransform());
1680 const Rect bounds(displayDevice->getBounds());
1681 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001682 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001683
Jeff Sharkey76488112017-02-27 14:15:18 -07001684 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wuf9fc8ee2017-11-16 11:45:52 -08001685 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001686 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1687 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001688 Region drawRegion(tr.transform(
1689 layer->visibleNonTransparentRegion));
1690 drawRegion.andSelf(bounds);
1691 if (!drawRegion.isEmpty()) {
1692 layersSortedByZ.add(layer);
1693 } else {
1694 // Clear out the HWC layer if this layer was
1695 // previously visible, but no longer is
Chia-I Wuf9fc8ee2017-11-16 11:45:52 -08001696 hwcLayerDestroyed = layer->hasHwcLayer(
1697 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001698 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1699 nullptr);
1700 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001701 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001702 // WM changes displayDevice->layerStack upon sleep/awake.
1703 // Here we make sure we delete the HWC layers even if
1704 // WM changed their layer stack.
Chia-I Wuf9fc8ee2017-11-16 11:45:52 -08001705 hwcLayerDestroyed = layer->hasHwcLayer(displayDevice->getHwcDisplayId());
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001706 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1707 nullptr);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001708 }
Chia-I Wuf9fc8ee2017-11-16 11:45:52 -08001709
1710 // If a layer is not going to get a release fence because
1711 // it is invisible, but it is also going to release its
1712 // old buffer, add it to the list of layers needing
1713 // fences.
1714 if (hwcLayerDestroyed) {
1715 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1716 mLayersWithQueuedFrames.cend(), layer);
1717 if (found != mLayersWithQueuedFrames.cend()) {
1718 layersNeedingFences.add(layer);
1719 }
1720 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001721 });
1722 }
1723 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wuf9fc8ee2017-11-16 11:45:52 -08001724 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001725 displayDevice->undefinedRegion.set(bounds);
1726 displayDevice->undefinedRegion.subtractSelf(
1727 tr.transform(opaqueRegion));
1728 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001729 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001730 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001731}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001732
Romain Guy0147a172017-06-01 13:53:56 -07001733mat4 SurfaceFlinger::computeSaturationMatrix() const {
1734 if (mSaturation == 1.0f) {
1735 return mat4();
1736 }
1737
1738 // Rec.709 luma coefficients
1739 float3 luminance{0.213f, 0.715f, 0.072f};
1740 luminance *= 1.0f - mSaturation;
1741 return mat4(
1742 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1743 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1744 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1745 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1746 );
1747}
1748
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001749// pickColorMode translates a given dataspace into the best available color mode.
1750// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001751android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001752 switch (dataSpace) {
1753 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1754 // system expects.
1755 case HAL_DATASPACE_UNKNOWN:
1756 case HAL_DATASPACE_SRGB:
1757 case HAL_DATASPACE_V0_SRGB:
1758 return HAL_COLOR_MODE_SRGB;
1759 break;
1760
1761 case HAL_DATASPACE_DISPLAY_P3:
1762 return HAL_COLOR_MODE_DISPLAY_P3;
1763 break;
1764
1765 default:
1766 // TODO (courtneygo): Do we want to assert an error here?
1767 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1768 dataSpace);
1769 return HAL_COLOR_MODE_SRGB;
1770 break;
1771 }
1772}
1773
Romain Guy0147a172017-06-01 13:53:56 -07001774android_dataspace SurfaceFlinger::bestTargetDataSpace(
1775 android_dataspace a, android_dataspace b) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001776 // Only support sRGB and Display-P3 right now.
1777 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1778 return HAL_DATASPACE_DISPLAY_P3;
1779 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001780 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1781 return HAL_DATASPACE_DISPLAY_P3;
1782 }
1783 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1784 return HAL_DATASPACE_DISPLAY_P3;
1785 }
1786
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001787 return HAL_DATASPACE_V0_SRGB;
1788}
1789
Mathias Agopiancd60f992012-08-16 16:28:27 -07001790void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001791 ATRACE_CALL();
1792 ALOGV("setUpHWComposer");
1793
Jesse Hall028dc8f2013-08-20 16:35:32 -07001794 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001795 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1796 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1797 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1798
1799 // If nothing has changed (!dirty), don't recompose.
1800 // If something changed, but we don't currently have any visible layers,
1801 // and didn't when we last did a composition, then skip it this time.
1802 // The second rule does two things:
1803 // - When all layers are removed from a display, we'll emit one black
1804 // frame, then nothing more until we get new layers.
1805 // - When a display is created with a private layer stack, we won't
1806 // emit any black frames until a layer is added to the layer stack.
1807 bool mustRecompose = dirty && !(empty && wasEmpty);
1808
1809 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1810 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1811 mustRecompose ? "doing" : "skipping",
1812 dirty ? "+" : "-",
1813 empty ? "+" : "-",
1814 wasEmpty ? "+" : "-");
1815
Dan Stoza71433162014-02-04 16:22:36 -08001816 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001817
1818 if (mustRecompose) {
1819 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1820 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001821 }
1822
Dan Stoza9e56aa02015-11-02 13:00:03 -08001823 // build the h/w work list
1824 if (CC_UNLIKELY(mGeometryInvalid)) {
1825 mGeometryInvalid = false;
1826 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1827 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1828 const auto hwcId = displayDevice->getHwcDisplayId();
1829 if (hwcId >= 0) {
1830 const Vector<sp<Layer>>& currentLayers(
1831 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001832 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001833 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001834 if (!layer->hasHwcLayer(hwcId)) {
1835 auto hwcLayer = mHwc->createLayer(hwcId);
1836 if (hwcLayer) {
1837 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1838 } else {
1839 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001840 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001841 }
1842 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001843
Robert Carrae060832016-11-28 10:51:00 -08001844 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001845 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001846 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001847 }
1848 }
1849 }
1850 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001851 }
Riley Andrews03414a12014-07-01 14:22:59 -07001852
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001853
Romain Guy0147a172017-06-01 13:53:56 -07001854 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001855
Dan Stoza9e56aa02015-11-02 13:00:03 -08001856 // Set the per-frame data
1857 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1858 auto& displayDevice = mDisplays[displayId];
1859 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001860
Dan Stoza9e56aa02015-11-02 13:00:03 -08001861 if (hwcId < 0) {
1862 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001863 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001864 if (colorMatrix != mPreviousColorMatrix) {
1865 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1866 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1867 "display %zd: %d", displayId, result);
1868 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001869 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1870 layer->setPerFrameData(displayDevice);
1871 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001872
1873 if (hasWideColorDisplay) {
1874 android_color_mode newColorMode;
1875 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1876
1877 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1878 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1879 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1880 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1881 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1882 }
1883 newColorMode = pickColorMode(newDataSpace);
1884
Thierry Strudel2924d012017-08-14 15:19:37 -07001885 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001886 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001887 }
1888
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001889 mPreviousColorMatrix = colorMatrix;
1890
Dan Stoza9e56aa02015-11-02 13:00:03 -08001891 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001892 auto& displayDevice = mDisplays[displayId];
1893 if (!displayDevice->isDisplayOn()) {
1894 continue;
1895 }
1896
1897 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001898 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1899 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001900 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001901}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001902
Mathias Agopiancd60f992012-08-16 16:28:27 -07001903void SurfaceFlinger::doComposition() {
1904 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001905 ALOGV("doComposition");
1906
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001907 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001908 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001909 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001910 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001911 // transform the dirty region into this screen's coordinate space
1912 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001913
1914 // repaint the framebuffer (if needed)
1915 doDisplayComposition(hw, dirtyRegion);
1916
Mathias Agopiancd60f992012-08-16 16:28:27 -07001917 hw->dirtyRegion.clear();
1918 hw->flip(hw->swapRegion);
1919 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001920 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001921 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001922 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001923}
1924
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001925void SurfaceFlinger::postFramebuffer()
1926{
Mathias Agopian841cde52012-03-01 15:44:37 -08001927 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001928 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001929
Mathias Agopiana44b0412011-10-16 18:46:35 -07001930 const nsecs_t now = systemTime();
1931 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001932
Dan Stoza9e56aa02015-11-02 13:00:03 -08001933 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1934 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001935 if (!displayDevice->isDisplayOn()) {
1936 continue;
1937 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001938 const auto hwcId = displayDevice->getHwcDisplayId();
1939 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001940 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001941 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001942 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001943 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001944 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08001945 // The layer buffer from the previous frame (if any) is released
1946 // by HWC only when the release fence from this frame (if any) is
1947 // signaled. Always get the release fence from HWC first.
1948 auto hwcLayer = layer->getHwcLayer(hwcId);
1949 sp<Fence> releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
1950
1951 // If the layer was client composited in the previous frame, we
1952 // need to merge with the previous client target acquire fence.
1953 // Since we do not track that, always merge with the current
1954 // client target acquire fence when it is available, even though
1955 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001956 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08001957 releaseFence = Fence::merge("LayerRelease", releaseFence,
1958 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001959 }
Chia-I Wu7b549592017-11-15 09:14:57 -08001960
Dan Stoza9e56aa02015-11-02 13:00:03 -08001961 layer->onLayerDisplayed(releaseFence);
1962 }
Chia-I Wuf9fc8ee2017-11-16 11:45:52 -08001963
1964 // We've got a list of layers needing fences, that are disjoint with
1965 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
1966 // supply them with the present fence.
1967 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
1968 sp<Fence> presentFence = mHwc->getPresentFence(hwcId);
1969 for (auto& layer : displayDevice->getLayersNeedingFences()) {
1970 layer->onLayerDisplayed(presentFence);
1971 }
1972 }
1973
Dan Stoza9e56aa02015-11-02 13:00:03 -08001974 if (hwcId >= 0) {
1975 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001976 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001977 }
1978
Mathias Agopiana44b0412011-10-16 18:46:35 -07001979 mLastSwapBufferTime = systemTime() - now;
1980 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001981
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001982 // |mStateLock| not needed as we are on the main thread
1983 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07001984 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1985 logFrameStats();
1986 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001987}
1988
Mathias Agopian87baae12012-07-31 12:38:26 -07001989void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001990{
Mathias Agopian841cde52012-03-01 15:44:37 -08001991 ATRACE_CALL();
1992
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001993 // here we keep a copy of the drawing state (that is the state that's
1994 // going to be overwritten by handleTransactionLocked()) outside of
1995 // mStateLock so that the side-effects of the State assignment
1996 // don't happen with mStateLock held (which can cause deadlocks).
1997 State drawingState(mDrawingState);
1998
Mathias Agopianca4d3602011-05-19 15:38:14 -07001999 Mutex::Autolock _l(mStateLock);
2000 const nsecs_t now = systemTime();
2001 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002002
Mathias Agopianca4d3602011-05-19 15:38:14 -07002003 // Here we're guaranteed that some transaction flags are set
2004 // so we can call handleTransactionLocked() unconditionally.
2005 // We call getTransactionFlags(), which will also clear the flags,
2006 // with mStateLock held to guarantee that mCurrentState won't change
2007 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002008
Mathias Agopiane57f2922012-08-09 16:29:12 -07002009 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002010 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002011
Mathias Agopianca4d3602011-05-19 15:38:14 -07002012 mLastTransactionTime = systemTime() - now;
2013 mDebugInTransaction = 0;
2014 invalidateHwcGeometry();
2015 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002016}
2017
Mathias Agopian87baae12012-07-31 12:38:26 -07002018void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002019{
Dan Stoza7dde5992015-05-22 09:51:44 -07002020 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002021 mCurrentState.traverseInZOrder([](Layer* layer) {
2022 layer->notifyAvailableFrames();
2023 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002024
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002025 /*
2026 * Traversal of the children
2027 * (perform the transaction for each of them if needed)
2028 */
2029
Mathias Agopian3559b072012-08-15 13:46:03 -07002030 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002031 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002032 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002033 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002034
2035 const uint32_t flags = layer->doTransaction(0);
2036 if (flags & Layer::eVisibleRegion)
2037 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002038 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002039 }
2040
2041 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002042 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002043 */
2044
Mathias Agopiane57f2922012-08-09 16:29:12 -07002045 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002046 // here we take advantage of Vector's copy-on-write semantics to
2047 // improve performance by skipping the transaction entirely when
2048 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07002049 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2050 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002051 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002052 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07002053 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07002054 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07002055
2056 // find the displays that were removed
2057 // (ie: in drawing state but not in current state)
2058 // also handle displays that changed
2059 // (ie: displays that are in both lists)
2060 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002061 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2062 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002063 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002064 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07002065 // Call makeCurrent() on the primary display so we can
2066 // be sure that nothing associated with this display
2067 // is current.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002068 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
Mathias Agopian875d8e12013-06-07 15:35:48 -07002069 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002070 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
Jesse Hall02d86562013-03-25 14:43:23 -07002071 if (hw != NULL)
2072 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07002073 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08002074 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07002075 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07002076 } else {
2077 ALOGW("trying to remove the main display");
2078 }
2079 } else {
2080 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07002081 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002082 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08002083 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2084 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07002085 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002086 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07002087 // recreating the DisplayDevice, so we just remove it
2088 // from the drawing state, so that it get re-added
2089 // below.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002090 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
Jesse Hall02d86562013-03-25 14:43:23 -07002091 if (hw != NULL)
2092 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07002093 mDisplays.removeItem(display);
2094 mDrawingState.displays.removeItemsAt(i);
2095 dc--; i--;
2096 // at this point we must loop to the next item
2097 continue;
2098 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002099
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002100 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07002101 if (disp != NULL) {
2102 if (state.layerStack != draw[i].layerStack) {
2103 disp->setLayerStack(state.layerStack);
2104 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002105 if ((state.orientation != draw[i].orientation)
2106 || (state.viewport != draw[i].viewport)
2107 || (state.frame != draw[i].frame))
2108 {
2109 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002110 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07002111 }
Michael Lentine47e45402014-07-18 15:34:25 -07002112 if (state.width != draw[i].width || state.height != draw[i].height) {
2113 disp->setDisplaySize(state.width, state.height);
2114 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002115 }
2116 }
2117 }
2118
2119 // find displays that were added
2120 // (ie: in current state but not in drawing state)
2121 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002122 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002123 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002124
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002125 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002126 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002127 sp<IGraphicBufferProducer> bqProducer;
2128 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian0556d792017-03-22 15:49:32 -07002129 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002130
Dan Stoza9e56aa02015-11-02 13:00:03 -08002131 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002132 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002133 // Virtual displays without a surface are dormant:
2134 // they have external state (layer stack, projection,
2135 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002136 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002137
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002138 // Allow VR composer to use virtual displays.
2139 if (mUseHwcVirtualDisplays || mHwc == mVrHwc) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002140 int width = 0;
2141 int status = state.surface->query(
2142 NATIVE_WINDOW_WIDTH, &width);
2143 ALOGE_IF(status != NO_ERROR,
2144 "Unable to query width (%d)", status);
2145 int height = 0;
2146 status = state.surface->query(
2147 NATIVE_WINDOW_HEIGHT, &height);
2148 ALOGE_IF(status != NO_ERROR,
2149 "Unable to query height (%d)", status);
2150 int intFormat = 0;
2151 status = state.surface->query(
2152 NATIVE_WINDOW_FORMAT, &intFormat);
2153 ALOGE_IF(status != NO_ERROR,
2154 "Unable to query format (%d)", status);
2155 auto format = static_cast<android_pixel_format_t>(
2156 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002157
Dan Stoza8cf150a2016-08-02 10:27:31 -07002158 mHwc->allocateVirtualDisplay(width, height, &format,
2159 &hwcId);
2160 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002161
Dan Stoza5cf424b2016-05-20 14:02:39 -07002162 // TODO: Plumb requested format back up to consumer
2163
Dan Stoza9e56aa02015-11-02 13:00:03 -08002164 sp<VirtualDisplaySurface> vds =
2165 new VirtualDisplaySurface(*mHwc,
2166 hwcId, state.surface, bqProducer,
2167 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002168
2169 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002170 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002171 }
2172 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002173 ALOGE_IF(state.surface!=NULL,
2174 "adding a supported display, but rendering "
2175 "surface is provided (%p), ignoring it",
2176 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002177
2178 hwcId = state.type;
2179 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2180 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002181 }
2182
2183 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002184 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002185 sp<DisplayDevice> hw =
2186 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2187 dispSurface, producer,
2188 mRenderEngine->getEGLConfig(),
2189 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002190 hw->setLayerStack(state.layerStack);
2191 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002192 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002193 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002194 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002195 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002196 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002197 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002198 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002199 }
2200 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002201 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002202 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002203
Mathias Agopian84300952012-11-21 16:02:13 -08002204 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2205 // The transform hint might have changed for some layers
2206 // (either because a display has changed, or because a layer
2207 // as changed).
2208 //
2209 // Walk through all the layers in currentLayers,
2210 // and update their transform hint.
2211 //
2212 // If a layer is visible only on a single display, then that
2213 // display is used to calculate the hint, otherwise we use the
2214 // default display.
2215 //
2216 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2217 // the hint is set before we acquire a buffer from the surface texture.
2218 //
2219 // NOTE: layer transactions have taken place already, so we use their
2220 // drawing state. However, SurfaceFlinger's own transaction has not
2221 // happened yet, so we must use the current state layer list
2222 // (soon to become the drawing state list).
2223 //
2224 sp<const DisplayDevice> disp;
2225 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002226 bool first = true;
2227 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002228 // NOTE: we rely on the fact that layers are sorted by
2229 // layerStack first (so we don't have to traverse the list
2230 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002231 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002232 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002233 currentlayerStack = layerStack;
2234 // figure out if this layerstack is mirrored
2235 // (more than one display) if so, pick the default display,
2236 // if not, pick the only display it's on.
2237 disp.clear();
2238 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2239 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002240 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian84300952012-11-21 16:02:13 -08002241 if (disp == NULL) {
George Burgess IV406a2852017-08-29 17:57:25 -07002242 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002243 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002244 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002245 break;
2246 }
2247 }
2248 }
2249 }
Chet Haase91d25932013-04-11 15:24:55 -07002250 if (disp == NULL) {
2251 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2252 // redraw after transform hint changes. See bug 8508397.
2253
2254 // could be null when this layer is using a layerStack
2255 // that is not visible on any display. Also can occur at
2256 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002257 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002258 }
Chet Haase91d25932013-04-11 15:24:55 -07002259 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002260
2261 first = false;
2262 });
Mathias Agopian84300952012-11-21 16:02:13 -08002263 }
2264
2265
Mathias Agopian3559b072012-08-15 13:46:03 -07002266 /*
2267 * Perform our own transaction if needed
2268 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002269
2270 if (mLayersAdded) {
2271 mLayersAdded = false;
2272 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002273 mVisibleRegionsDirty = true;
2274 }
2275
2276 // some layers might have been removed, so
2277 // we need to update the regions they're exposing.
2278 if (mLayersRemoved) {
2279 mLayersRemoved = false;
2280 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002281 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002282 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002283 // this layer is not visible anymore
2284 // TODO: we could traverse the tree from front to back and
2285 // compute the actual visible region
2286 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002287 Region visibleReg;
2288 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002289 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002290 }
Robert Carr2047fae2016-11-28 14:09:09 -08002291 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002292 }
2293
2294 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002295
2296 updateCursorAsync();
2297}
2298
2299void SurfaceFlinger::updateCursorAsync()
2300{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002301 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2302 auto& displayDevice = mDisplays[displayId];
2303 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002304 continue;
2305 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002306
2307 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2308 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002309 }
2310 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002311}
2312
2313void SurfaceFlinger::commitTransaction()
2314{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002315 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002316 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002317 for (const auto& l : mLayersPendingRemoval) {
2318 recordBufferingStats(l->getName().string(),
2319 l->getOccupancyHistory(true));
2320 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002321 }
2322 mLayersPendingRemoval.clear();
2323 }
2324
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002325 // If this transaction is part of a window animation then the next frame
2326 // we composite should be considered an animation as well.
2327 mAnimCompositionPending = mAnimTransactionPending;
2328
Mathias Agopian4fec8732012-06-29 14:12:52 -07002329 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002330 mDrawingState.traverseInZOrder([](Layer* layer) {
2331 layer->commitChildList();
2332 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002333 mTransactionPending = false;
2334 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002335 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002336}
2337
Chia-I Wuab0c3192017-08-01 11:29:00 -07002338void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002339 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002340{
Mathias Agopian841cde52012-03-01 15:44:37 -08002341 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002342 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002343
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002344 Region aboveOpaqueLayers;
2345 Region aboveCoveredLayers;
2346 Region dirty;
2347
Mathias Agopian87baae12012-07-31 12:38:26 -07002348 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002349
Robert Carr2047fae2016-11-28 14:09:09 -08002350 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002351 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002352 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002353
Jesse Hall01e29052013-02-19 16:13:35 -08002354 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002355 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002356 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002357
Mathias Agopianab028732010-03-16 16:41:46 -07002358 /*
2359 * opaqueRegion: area of a surface that is fully opaque.
2360 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002361 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002362
2363 /*
2364 * visibleRegion: area of a surface that is visible on screen
2365 * and not fully transparent. This is essentially the layer's
2366 * footprint minus the opaque regions above it.
2367 * Areas covered by a translucent surface are considered visible.
2368 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002369 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002370
2371 /*
2372 * coveredRegion: area of a surface that is covered by all
2373 * visible regions above it (which includes the translucent areas).
2374 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002375 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002376
Jesse Halla8026d22012-09-25 13:25:04 -07002377 /*
2378 * transparentRegion: area of a surface that is hinted to be completely
2379 * transparent. This is only used to tell when the layer has no visible
2380 * non-transparent regions and can be removed from the layer list. It
2381 * does not affect the visibleRegion of this layer or any layers
2382 * beneath it. The hint may not be correct if apps don't respect the
2383 * SurfaceView restrictions (which, sadly, some don't).
2384 */
2385 Region transparentRegion;
2386
Mathias Agopianab028732010-03-16 16:41:46 -07002387
2388 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002389 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002390 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002391 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002392 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002393 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002394 if (!visibleRegion.isEmpty()) {
2395 // Remove the transparent area from the visible region
2396 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002397 if (tr.preserveRects()) {
2398 // transform the transparent region
2399 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002400 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002401 // transformation too complex, can't do the
2402 // transparent region optimization.
2403 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002404 }
Mathias Agopianab028732010-03-16 16:41:46 -07002405 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002406
Mathias Agopianab028732010-03-16 16:41:46 -07002407 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002408 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002409 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002410 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2411 // the opaque region is the layer's footprint
2412 opaqueRegion = visibleRegion;
2413 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002414 }
2415 }
2416
Mathias Agopianab028732010-03-16 16:41:46 -07002417 // Clip the covered region to the visible region
2418 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2419
2420 // Update aboveCoveredLayers for next (lower) layer
2421 aboveCoveredLayers.orSelf(visibleRegion);
2422
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002423 // subtract the opaque region covered by the layers above us
2424 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002425
2426 // compute this layer's dirty region
2427 if (layer->contentDirty) {
2428 // we need to invalidate the whole region
2429 dirty = visibleRegion;
2430 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002431 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002432 layer->contentDirty = false;
2433 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002434 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002435 * the exposed region consists of two components:
2436 * 1) what's VISIBLE now and was COVERED before
2437 * 2) what's EXPOSED now less what was EXPOSED before
2438 *
2439 * note that (1) is conservative, we start with the whole
2440 * visible region but only keep what used to be covered by
2441 * something -- which mean it may have been exposed.
2442 *
2443 * (2) handles areas that were not covered by anything but got
2444 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002445 */
Mathias Agopianab028732010-03-16 16:41:46 -07002446 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002447 const Region oldVisibleRegion = layer->visibleRegion;
2448 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002449 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2450 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002451 }
2452 dirty.subtractSelf(aboveOpaqueLayers);
2453
2454 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002455 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002456
Mathias Agopianab028732010-03-16 16:41:46 -07002457 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002458 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002459
Jesse Halla8026d22012-09-25 13:25:04 -07002460 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002461 layer->setVisibleRegion(visibleRegion);
2462 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002463 layer->setVisibleNonTransparentRegion(
2464 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002465 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002466
Mathias Agopian87baae12012-07-31 12:38:26 -07002467 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002468}
2469
Chia-I Wuab0c3192017-08-01 11:29:00 -07002470void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002471 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002472 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002473 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002474 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002475 }
2476 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002477}
2478
Dan Stoza6b9454d2014-11-07 16:00:59 -08002479bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002480{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002481 ALOGV("handlePageFlip");
2482
Brian Andersond6927fb2016-07-23 23:37:30 -07002483 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002484
Mathias Agopian4fec8732012-06-29 14:12:52 -07002485 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002486 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002487 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002488
2489 // Store the set of layers that need updates. This set must not change as
2490 // buffers are being latched, as this could result in a deadlock.
2491 // Example: Two producers share the same command stream and:
2492 // 1.) Layer 0 is latched
2493 // 2.) Layer 0 gets a new frame
2494 // 2.) Layer 1 gets a new frame
2495 // 3.) Layer 1 is latched.
2496 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2497 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002498 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002499 if (layer->hasQueuedFrame()) {
2500 frameQueued = true;
2501 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002502 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002503 } else {
2504 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002505 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002506 } else {
2507 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002508 }
Robert Carr2047fae2016-11-28 14:09:09 -08002509 });
2510
Dan Stoza9e56aa02015-11-02 13:00:03 -08002511 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002512 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002513 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002514 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002515 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002516 newDataLatched = true;
2517 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002518 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002519
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002520 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002521
2522 // If we will need to wake up at some time in the future to deal with a
2523 // queued frame that shouldn't be displayed during this vsync period, wake
2524 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002525 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002526 signalLayerUpdate();
2527 }
2528
2529 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002530 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002531}
2532
Mathias Agopianad456f92011-01-13 17:53:01 -08002533void SurfaceFlinger::invalidateHwcGeometry()
2534{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002535 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002536}
2537
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002538
Fabien Sanglard830b8472016-11-30 16:35:58 -08002539void SurfaceFlinger::doDisplayComposition(
2540 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002541 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002542{
Dan Stoza71433162014-02-04 16:22:36 -08002543 // We only need to actually compose the display if:
2544 // 1) It is being handled by hardware composer, which may need this to
2545 // keep its virtual display state machine in sync, or
2546 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002547 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002548 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002549 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002550 return;
2551 }
2552
Dan Stoza9e56aa02015-11-02 13:00:03 -08002553 ALOGV("doDisplayComposition");
2554
Mathias Agopian87baae12012-07-31 12:38:26 -07002555 Region dirtyRegion(inDirtyRegion);
2556
Mathias Agopianb8a55602009-06-26 19:06:36 -07002557 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002558 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002559
Fabien Sanglard830b8472016-11-30 16:35:58 -08002560 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002561 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002562 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2563 // takes a rectangle, we must make sure to update that whole
2564 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002565 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002566 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002567 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002568 // We need to redraw the rectangle that will be updated
2569 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002570 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002571 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002572 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002573 } else {
2574 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002575 dirtyRegion.set(displayDevice->bounds());
2576 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002577 }
2578 }
2579
Fabien Sanglard830b8472016-11-30 16:35:58 -08002580 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002581
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002582 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002583 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002584
2585 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002586 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002587}
2588
Dan Stoza9e56aa02015-11-02 13:00:03 -08002589bool SurfaceFlinger::doComposeSurfaces(
2590 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002591{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002592 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002593
Dan Stoza9e56aa02015-11-02 13:00:03 -08002594 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002595
2596 mat4 oldColorMatrix;
2597 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2598 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2599 if (applyColorMatrix) {
2600 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2601 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2602 }
2603
Dan Stoza9e56aa02015-11-02 13:00:03 -08002604 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2605 if (hasClientComposition) {
2606 ALOGV("hasClientComposition");
2607
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002608#ifdef USE_HWC2
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002609 mRenderEngine->setWideColor(displayDevice->getWideColorSupport());
Romain Guy88d37dd2017-05-26 17:57:05 -07002610 mRenderEngine->setColorMode(displayDevice->getActiveColorMode());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002611#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002612 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002613 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002614 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002615 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002616
2617 // |mStateLock| not needed as we are on the main thread
2618 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002619 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2620 }
2621 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002622 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002623
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002624 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002625 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2626 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002627 // when using overlays, we assume a fully transparent framebuffer
2628 // NOTE: we could reduce how much we need to clear, for instance
2629 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002630 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002631 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002632 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002633 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002634 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002635 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002636
2637 // we remove the scissor part
2638 // we're left with the letterbox region
2639 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002640 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002641
2642 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002643 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002644
2645 // but limit it to the dirty region
2646 region.andSelf(dirty);
2647
Mathias Agopianb9494d52012-04-18 02:28:45 -07002648 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002649 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002650 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002651 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002652 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002653 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002654
Dan Stoza9e56aa02015-11-02 13:00:03 -08002655 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002656 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002657 // scissor on the main display. It should never be needed
2658 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002659 const Rect& bounds(displayDevice->getBounds());
2660 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002661 if (scissor != bounds) {
2662 // scissor doesn't match the screen's dimensions, so we
2663 // need to clear everything outside of it and enable
2664 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002665
Mathias Agopianf45c5102012-10-24 16:29:17 -07002666 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002667 const uint32_t height = displayDevice->getHeight();
2668 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002669 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002670 }
2671 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002672 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002673
Mathias Agopian85d751c2012-08-29 16:59:24 -07002674 /*
2675 * and then, render the layers targeted at the framebuffer
2676 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002677
Dan Stoza9e56aa02015-11-02 13:00:03 -08002678 ALOGV("Rendering client layers");
2679 const Transform& displayTransform = displayDevice->getTransform();
2680 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002681 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002682 bool firstLayer = true;
2683 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2684 const Region clip(dirty.intersect(
2685 displayTransform.transform(layer->visibleRegion)));
2686 ALOGV("Layer: %s", layer->getName().string());
2687 ALOGV(" Composition type: %s",
2688 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002689 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002690 switch (layer->getCompositionType(hwcId)) {
2691 case HWC2::Composition::Cursor:
2692 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002693 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002694 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002695 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002696 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2697 layer->isOpaque(state) && (state.alpha == 1.0f)
2698 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002699 // never clear the very first layer since we're
2700 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002701 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002702 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002703 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002704 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002705 case HWC2::Composition::Client: {
2706 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002707 break;
2708 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002709 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002710 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002711 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002712 } else {
2713 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002714 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002715 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002716 }
2717 } else {
2718 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002719 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002720 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002721 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002722 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002723 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002724 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002725 }
2726 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002727
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002728 if (applyColorMatrix) {
2729 getRenderEngine().setupColorTransform(oldColorMatrix);
2730 }
2731
Mathias Agopianf45c5102012-10-24 16:29:17 -07002732 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002733 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002734 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002735}
2736
Fabien Sanglard830b8472016-11-30 16:35:58 -08002737void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2738 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002739 RenderEngine& engine(getRenderEngine());
2740 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002741}
2742
Dan Stoza7d89d062015-04-30 13:29:25 -07002743status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002744 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002745 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002746 const sp<Layer>& lbc,
2747 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002748{
Dan Stoza7d89d062015-04-30 13:29:25 -07002749 // add this layer to the current state list
2750 {
2751 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002752 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002753 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2754 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002755 return NO_MEMORY;
2756 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002757 if (parent == nullptr) {
2758 mCurrentState.layersSortedByZ.add(lbc);
2759 } else {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002760 if (mCurrentState.layersSortedByZ.indexOf(parent) < 0) {
2761 ALOGE("addClientLayer called with a removed parent");
2762 return NAME_NOT_FOUND;
2763 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002764 parent->addChild(lbc);
2765 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002766
Dan Stoza7d89d062015-04-30 13:29:25 -07002767 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002768 mLayersAdded = true;
2769 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002770 }
2771
Mathias Agopian96f08192010-06-02 23:28:45 -07002772 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002773 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002774
Dan Stoza7d89d062015-04-30 13:29:25 -07002775 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002776}
2777
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002778status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002779 Mutex::Autolock _l(mStateLock);
2780
Robert Carr1f0a16a2016-10-24 16:27:39 -07002781 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002782 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002783 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002784 if (topLevelOnly) {
2785 return NO_ERROR;
2786 }
2787
Chia-I Wu98f1c102017-05-30 14:54:08 -07002788 sp<Layer> ancestor = p;
2789 while (ancestor->getParent() != nullptr) {
2790 ancestor = ancestor->getParent();
2791 }
2792 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2793 ALOGE("removeLayer called with a layer whose parent has been removed");
2794 return NAME_NOT_FOUND;
2795 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002796
2797 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002798 } else {
2799 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002800 }
2801
Robert Carr136e2f62017-02-08 17:54:29 -08002802 // As a matter of normal operation, the LayerCleaner will produce a second
2803 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2804 // so we will succeed in promoting it, but it's already been removed
2805 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2806 // otherwise something has gone wrong and we are leaking the layer.
2807 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002808 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2809 layer->getName().string(),
2810 (p != nullptr) ? p->getName().string() : "no-parent");
2811 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002812 } else if (index < 0) {
2813 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002814 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002815
2816 mLayersPendingRemoval.add(layer);
2817 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002818 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002819 setTransactionFlags(eTransactionNeeded);
2820 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002821}
2822
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002823uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002824 return android_atomic_release_load(&mTransactionFlags);
2825}
2826
Mathias Agopian3f844832013-08-07 21:24:32 -07002827uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002828 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2829}
2830
Mathias Agopian3f844832013-08-07 21:24:32 -07002831uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002832 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2833 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002834 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002835 }
2836 return old;
2837}
2838
Mathias Agopian8b33f032012-07-24 20:43:54 -07002839void SurfaceFlinger::setTransactionState(
2840 const Vector<ComposerState>& state,
2841 const Vector<DisplayState>& displays,
2842 uint32_t flags)
2843{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002844 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002845 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002846 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002847
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002848 if (flags & eAnimation) {
2849 // For window updates that are part of an animation we must wait for
2850 // previous animation "frames" to be handled.
2851 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002852 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002853 if (CC_UNLIKELY(err != NO_ERROR)) {
2854 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002855 // caller after a few seconds.
2856 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2857 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002858 mAnimTransactionPending = false;
2859 break;
2860 }
2861 }
2862 }
2863
Mathias Agopiane57f2922012-08-09 16:29:12 -07002864 size_t count = displays.size();
2865 for (size_t i=0 ; i<count ; i++) {
2866 const DisplayState& s(displays[i]);
2867 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002868 }
2869
Mathias Agopiane57f2922012-08-09 16:29:12 -07002870 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002871 for (size_t i=0 ; i<count ; i++) {
2872 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002873 // Here we need to check that the interface we're given is indeed
2874 // one of our own. A malicious client could give us a NULL
2875 // IInterface, or one of its own or even one of our own but a
2876 // different type. All these situations would cause us to crash.
2877 //
2878 // NOTE: it would be better to use RTTI as we could directly check
2879 // that we have a Client*. however, RTTI is disabled in Android.
2880 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002881 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002882 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002883 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002884 sp<Client> client( static_cast<Client *>(s.client.get()) );
2885 transactionFlags |= setClientStateLocked(client, s.state);
2886 }
2887 }
2888 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002889 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002890
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02002891 // If a synchronous transaction is explicitly requested without any changes, force a transaction
2892 // anyway. This can be used as a flush mechanism for previous async transactions.
2893 // Empty animation transaction can be used to simulate back-pressure, so also force a
2894 // transaction for empty animation transactions.
2895 if (transactionFlags == 0 &&
2896 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07002897 transactionFlags = eTransactionNeeded;
2898 }
2899
Mathias Agopian386aa982011-11-07 21:58:03 -08002900 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002901 if (mInterceptor.isEnabled()) {
2902 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2903 }
Irvel468051e2016-06-13 16:44:44 -07002904
Mathias Agopian386aa982011-11-07 21:58:03 -08002905 // this triggers the transaction
2906 setTransactionFlags(transactionFlags);
2907
2908 // if this is a synchronous transaction, wait for it to take effect
2909 // before returning.
2910 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002911 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002912 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002913 if (flags & eAnimation) {
2914 mAnimTransactionPending = true;
2915 }
2916 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002917 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2918 if (CC_UNLIKELY(err != NO_ERROR)) {
2919 // just in case something goes wrong in SF, return to the
2920 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002921 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2922 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002923 break;
2924 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002925 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002926 }
2927}
2928
Mathias Agopiane57f2922012-08-09 16:29:12 -07002929uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2930{
Jesse Hall9a143922012-10-04 16:29:19 -07002931 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2932 if (dpyIdx < 0)
2933 return 0;
2934
Mathias Agopiane57f2922012-08-09 16:29:12 -07002935 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002936 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002937 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002938 const uint32_t what = s.what;
2939 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002940 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002941 disp.surface = s.surface;
2942 flags |= eDisplayTransactionNeeded;
2943 }
2944 }
2945 if (what & DisplayState::eLayerStackChanged) {
2946 if (disp.layerStack != s.layerStack) {
2947 disp.layerStack = s.layerStack;
2948 flags |= eDisplayTransactionNeeded;
2949 }
2950 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002951 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002952 if (disp.orientation != s.orientation) {
2953 disp.orientation = s.orientation;
2954 flags |= eDisplayTransactionNeeded;
2955 }
2956 if (disp.frame != s.frame) {
2957 disp.frame = s.frame;
2958 flags |= eDisplayTransactionNeeded;
2959 }
2960 if (disp.viewport != s.viewport) {
2961 disp.viewport = s.viewport;
2962 flags |= eDisplayTransactionNeeded;
2963 }
2964 }
Michael Lentine47e45402014-07-18 15:34:25 -07002965 if (what & DisplayState::eDisplaySizeChanged) {
2966 if (disp.width != s.width) {
2967 disp.width = s.width;
2968 flags |= eDisplayTransactionNeeded;
2969 }
2970 if (disp.height != s.height) {
2971 disp.height = s.height;
2972 flags |= eDisplayTransactionNeeded;
2973 }
2974 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002975 }
2976 return flags;
2977}
2978
2979uint32_t SurfaceFlinger::setClientStateLocked(
2980 const sp<Client>& client,
2981 const layer_state_t& s)
2982{
2983 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002984 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002985 if (layer != 0) {
2986 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002987 bool geometryAppliesWithResize =
2988 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002989 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002990 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002991 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002992 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002993 }
2994 if (what & layer_state_t::eLayerChanged) {
2995 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002996 const auto& p = layer->getParent();
2997 if (p == nullptr) {
2998 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2999 if (layer->setLayer(s.z) && idx >= 0) {
3000 mCurrentState.layersSortedByZ.removeAt(idx);
3001 mCurrentState.layersSortedByZ.add(layer);
3002 // we need traversal (state changed)
3003 // AND transaction (list changed)
3004 flags |= eTransactionNeeded|eTraversalNeeded;
3005 }
3006 } else {
3007 if (p->setChildLayer(layer, s.z)) {
3008 flags |= eTransactionNeeded|eTraversalNeeded;
3009 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003010 }
3011 }
Robert Carrdb66e622017-04-10 16:55:57 -07003012 if (what & layer_state_t::eRelativeLayerChanged) {
3013 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z)) {
3014 flags |= eTransactionNeeded|eTraversalNeeded;
3015 }
3016 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003017 if (what & layer_state_t::eSizeChanged) {
3018 if (layer->setSize(s.w, s.h)) {
3019 flags |= eTraversalNeeded;
3020 }
3021 }
3022 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003023 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003024 flags |= eTraversalNeeded;
3025 }
3026 if (what & layer_state_t::eMatrixChanged) {
3027 if (layer->setMatrix(s.matrix))
3028 flags |= eTraversalNeeded;
3029 }
3030 if (what & layer_state_t::eTransparentRegionChanged) {
3031 if (layer->setTransparentRegionHint(s.transparentRegion))
3032 flags |= eTraversalNeeded;
3033 }
Dan Stoza23116082015-06-18 14:58:39 -07003034 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003035 if (layer->setFlags(s.flags, s.mask))
3036 flags |= eTraversalNeeded;
3037 }
3038 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07003039 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003040 flags |= eTraversalNeeded;
3041 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003042 if (what & layer_state_t::eFinalCropChanged) {
Robert Carr8d5227b2017-03-16 15:41:03 -07003043 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003044 flags |= eTraversalNeeded;
3045 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003046 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003047 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003048 // We only allow setting layer stacks for top level layers,
3049 // everything else inherits layer stack from its parent.
3050 if (layer->hasParent()) {
3051 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3052 layer->getName().string());
3053 } else if (idx < 0) {
3054 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3055 "that also does not appear in the top level layer list. Something"
3056 " has gone wrong.", layer->getName().string());
3057 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003058 mCurrentState.layersSortedByZ.removeAt(idx);
3059 mCurrentState.layersSortedByZ.add(layer);
3060 // we need traversal (state changed)
3061 // AND transaction (list changed)
3062 flags |= eTransactionNeeded|eTraversalNeeded;
3063 }
3064 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003065 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08003066 if (s.barrierHandle != nullptr) {
3067 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3068 } else if (s.barrierGbp != nullptr) {
3069 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3070 if (authenticateSurfaceTextureLocked(gbp)) {
3071 const auto& otherLayer =
3072 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3073 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3074 } else {
3075 ALOGE("Attempt to defer transaction to to an"
3076 " unrecognized GraphicBufferProducer");
3077 }
3078 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003079 // We don't trigger a traversal here because if no other state is
3080 // changed, we don't want this to cause any more work
3081 }
Robert Carr1db73f62016-12-21 12:58:51 -08003082 if (what & layer_state_t::eReparentChildren) {
3083 if (layer->reparentChildren(s.reparentHandle)) {
3084 flags |= eTransactionNeeded|eTraversalNeeded;
3085 }
3086 }
Robert Carr9524cb32017-02-13 11:32:32 -08003087 if (what & layer_state_t::eDetachChildren) {
3088 layer->detachChildren();
3089 }
Robert Carrc3574f72016-03-24 12:19:32 -07003090 if (what & layer_state_t::eOverrideScalingModeChanged) {
3091 layer->setOverrideScalingMode(s.overrideScalingMode);
3092 // We don't trigger a traversal here because if no other state is
3093 // changed, we don't want this to cause any more work
3094 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003095 }
3096 return flags;
3097}
3098
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003099status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003100 const String8& name,
3101 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003102 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003103 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3104 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003105{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003106 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003107 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003108 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003109 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003110 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003111
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003112 status_t result = NO_ERROR;
3113
3114 sp<Layer> layer;
3115
Cody Northropbc755282017-03-31 12:00:08 -06003116 String8 uniqueName = getUniqueLayerName(name);
3117
Mathias Agopian3165cc22012-08-08 19:42:09 -07003118 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3119 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003120 result = createNormalLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003121 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003122 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003123 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07003124 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003125 result = createDimLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003126 uniqueName, w, h, flags,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003127 handle, gbp, &layer);
3128 break;
3129 default:
3130 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003131 break;
3132 }
3133
Dan Stoza7d89d062015-04-30 13:29:25 -07003134 if (result != NO_ERROR) {
3135 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003136 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003137
Chia-I Wuab0c3192017-08-01 11:29:00 -07003138 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3139 // TODO b/64227542
3140 if (windowType == 441731) {
3141 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3142 layer->setPrimaryDisplayOnly();
3143 }
3144
Albert Chaulk479c60c2017-01-27 14:21:34 -05003145 layer->setInfo(windowType, ownerUid);
3146
Robert Carr1f0a16a2016-10-24 16:27:39 -07003147 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003148 if (result != NO_ERROR) {
3149 return result;
3150 }
Irvelffc9efc2016-07-27 15:16:37 -07003151 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003152
3153 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003154 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003155}
3156
Cody Northropbc755282017-03-31 12:00:08 -06003157String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3158{
3159 bool matchFound = true;
3160 uint32_t dupeCounter = 0;
3161
3162 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3163 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3164
3165 // Loop over layers until we're sure there is no matching name
3166 while (matchFound) {
3167 matchFound = false;
3168 mDrawingState.traverseInZOrder([&](Layer* layer) {
3169 if (layer->getName() == uniqueName) {
3170 matchFound = true;
3171 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3172 }
3173 });
3174 }
3175
3176 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3177
3178 return uniqueName;
3179}
3180
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003181status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
3182 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3183 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003184{
3185 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003186 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003187 case PIXEL_FORMAT_TRANSPARENT:
3188 case PIXEL_FORMAT_TRANSLUCENT:
3189 format = PIXEL_FORMAT_RGBA_8888;
3190 break;
3191 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003192 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003193 break;
3194 }
3195
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003196 *outLayer = new Layer(this, client, name, w, h, flags);
3197 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
3198 if (err == NO_ERROR) {
3199 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003200 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003201 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003202
3203 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3204 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003205}
3206
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003207status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
3208 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3209 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003210{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003211 *outLayer = new LayerDim(this, client, name, w, h, flags);
3212 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003213 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003214 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003215}
3216
Mathias Agopianac9fa422013-02-11 16:40:36 -08003217status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003218{
Robert Carr9524cb32017-02-13 11:32:32 -08003219 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003220 status_t err = NO_ERROR;
3221 sp<Layer> l(client->getLayerUser(handle));
3222 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003223 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003224 err = removeLayer(l);
3225 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3226 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003227 }
3228 return err;
3229}
3230
Mathias Agopian13127d82013-03-05 17:47:11 -08003231status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003232{
Mathias Agopian67106042013-03-14 19:18:13 -07003233 // called by ~LayerCleaner() when all references to the IBinder (handle)
3234 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003235 sp<Layer> l = layer.promote();
3236 if (l == nullptr) {
3237 // The layer has already been removed, carry on
3238 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003239 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003240 // If we have a parent, then we can continue to live as long as it does.
3241 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003242}
3243
Mathias Agopianb60314a2012-04-10 22:09:54 -07003244// ---------------------------------------------------------------------------
3245
Andy McFadden13a082e2012-08-24 10:16:42 -07003246void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003247 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003248 Vector<ComposerState> state;
3249 Vector<DisplayState> displays;
3250 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003251 d.what = DisplayState::eDisplayProjectionChanged |
3252 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003253 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003254 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003255 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003256 d.frame.makeInvalid();
3257 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003258 d.width = 0;
3259 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003260 displays.add(d);
3261 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003262 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003263
Dan Stoza9e56aa02015-11-02 13:00:03 -08003264 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3265 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003266 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003267
Brian Andersond0010582017-03-07 13:20:31 -08003268 // Use phase of 0 since phase is not known.
3269 // Use latency of 0, which will snap to the ideal latency.
3270 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003271}
3272
3273void SurfaceFlinger::initializeDisplays() {
3274 class MessageScreenInitialized : public MessageBase {
3275 SurfaceFlinger* flinger;
3276 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003277 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003278 virtual bool handler() {
3279 flinger->onInitializeDisplays();
3280 return true;
3281 }
3282 };
3283 sp<MessageBase> msg = new MessageScreenInitialized(this);
3284 postMessageAsync(msg); // we may be called from main thread, use async message
3285}
3286
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003287void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
3288 int mode) {
3289 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3290 this);
3291 int32_t type = hw->getDisplayType();
3292 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003293
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003294 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003295 return;
3296 }
3297
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003298 hw->setPowerMode(mode);
3299 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3300 ALOGW("Trying to set power mode for virtual display");
3301 return;
3302 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003303
Irvelffc9efc2016-07-27 15:16:37 -07003304 if (mInterceptor.isEnabled()) {
3305 Mutex::Autolock _l(mStateLock);
3306 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3307 if (idx < 0) {
3308 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3309 return;
3310 }
3311 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3312 }
3313
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003314 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003315 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003316 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003317 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3318 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003319 // FIXME: eventthread only knows about the main display right now
3320 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003321 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003322 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003323
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003324 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003325 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003326 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003327
3328 struct sched_param param = {0};
3329 param.sched_priority = 1;
3330 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3331 ALOGW("Couldn't set SCHED_FIFO on display on");
3332 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003333 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003334 // Turn off the display
3335 struct sched_param param = {0};
3336 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3337 ALOGW("Couldn't set SCHED_OTHER on display off");
3338 }
3339
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003340 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003341 disableHardwareVsync(true); // also cancels any in-progress resync
3342
Mathias Agopiancde87a32012-09-13 14:09:01 -07003343 // FIXME: eventthread only knows about the main display right now
3344 mEventThread->onScreenReleased();
3345 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003346
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003347 getHwComposer().setPowerMode(type, mode);
3348 mVisibleRegionsDirty = true;
3349 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003350 } else if (mode == HWC_POWER_MODE_DOZE ||
3351 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003352 // Update display while dozing
3353 getHwComposer().setPowerMode(type, mode);
3354 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3355 // FIXME: eventthread only knows about the main display right now
3356 mEventThread->onScreenAcquired();
3357 resyncToHardwareVsync(true);
3358 }
3359 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3360 // Leave display going to doze
3361 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3362 disableHardwareVsync(true); // also cancels any in-progress resync
3363 // FIXME: eventthread only knows about the main display right now
3364 mEventThread->onScreenReleased();
3365 }
3366 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003367 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003368 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003369 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003370 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003371}
3372
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003373void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3374 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003375 SurfaceFlinger& mFlinger;
3376 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003377 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003378 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003379 MessageSetPowerMode(SurfaceFlinger& flinger,
3380 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3381 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003382 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003383 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003384 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003385 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003386 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003387 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003388 ALOGW("Attempt to set power mode = %d for virtual display",
3389 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003390 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003391 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003392 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003393 return true;
3394 }
3395 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003396 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003397 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003398}
3399
3400// ---------------------------------------------------------------------------
3401
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003402status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3403{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003404 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003405
Mathias Agopianbd115332013-04-18 16:41:04 -07003406 IPCThreadState* ipc = IPCThreadState::self();
3407 const int pid = ipc->getCallingPid();
3408 const int uid = ipc->getCallingUid();
3409 if ((uid != AID_SHELL) &&
3410 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003411 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003412 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003413 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003414 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003415 // (this would indicate SF is stuck, but we want to be able to
3416 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003417 status_t err = mStateLock.timedLock(s2ns(1));
3418 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003419 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003420 result.appendFormat(
3421 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3422 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003423 }
3424
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003425 bool dumpAll = true;
3426 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003427 size_t numArgs = args.size();
3428 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003429 if ((index < numArgs) &&
3430 (args[index] == String16("--list"))) {
3431 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003432 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003433 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003434 }
3435
3436 if ((index < numArgs) &&
3437 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003438 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003439 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003440 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003441 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003442
3443 if ((index < numArgs) &&
3444 (args[index] == String16("--latency-clear"))) {
3445 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003446 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003447 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003448 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003449
3450 if ((index < numArgs) &&
3451 (args[index] == String16("--dispsync"))) {
3452 index++;
3453 mPrimaryDispSync.dump(result);
3454 dumpAll = false;
3455 }
Dan Stozab90cf072015-03-05 11:05:59 -08003456
3457 if ((index < numArgs) &&
3458 (args[index] == String16("--static-screen"))) {
3459 index++;
3460 dumpStaticScreenStats(result);
3461 dumpAll = false;
3462 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003463
3464 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003465 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003466 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003467 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003468 dumpAll = false;
3469 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003470
3471 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3472 index++;
3473 dumpWideColorInfo(result);
3474 dumpAll = false;
3475 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003476 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003477
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003478 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003479 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003480 }
3481
Mathias Agopian9795c422009-08-26 16:36:26 -07003482 if (locked) {
3483 mStateLock.unlock();
3484 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003485 }
3486 write(fd, result.string(), result.size());
3487 return NO_ERROR;
3488}
3489
Dan Stozac7014012014-02-14 15:03:43 -08003490void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3491 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003492{
Robert Carr2047fae2016-11-28 14:09:09 -08003493 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003494 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003495 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003496}
3497
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003498void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003499 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003500{
3501 String8 name;
3502 if (index < args.size()) {
3503 name = String8(args[index]);
3504 index++;
3505 }
3506
Dan Stoza9e56aa02015-11-02 13:00:03 -08003507 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3508 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003509 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003510
3511 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003512 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003513 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003514 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003515 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003516 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003517 }
Robert Carr2047fae2016-11-28 14:09:09 -08003518 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003519 }
3520}
3521
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003522void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003523 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003524{
3525 String8 name;
3526 if (index < args.size()) {
3527 name = String8(args[index]);
3528 index++;
3529 }
3530
Robert Carr2047fae2016-11-28 14:09:09 -08003531 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003532 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003533 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003534 }
Robert Carr2047fae2016-11-28 14:09:09 -08003535 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003536
Svetoslavd85084b2014-03-20 10:28:31 -07003537 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003538}
3539
Jamie Gennis6547ff42013-07-16 20:12:42 -07003540// This should only be called from the main thread. Otherwise it would need
3541// the lock and should use mCurrentState rather than mDrawingState.
3542void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003543 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003544 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003545 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003546
3547 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3548}
3549
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003550void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003551{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003552 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003553 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3554
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003555 if (isLayerTripleBufferingDisabled())
3556 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003557
3558 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003559 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003560 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003561 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003562 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3563 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003564 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003565}
3566
Dan Stozab90cf072015-03-05 11:05:59 -08003567void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3568{
3569 result.appendFormat("Static screen stats:\n");
3570 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3571 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3572 float percent = 100.0f *
3573 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3574 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3575 b + 1, bucketTimeSec, percent);
3576 }
3577 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3578 float percent = 100.0f *
3579 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3580 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3581 NUM_BUCKETS - 1, bucketTimeSec, percent);
3582}
3583
Dan Stozae77c7662016-05-13 11:37:28 -07003584void SurfaceFlinger::recordBufferingStats(const char* layerName,
3585 std::vector<OccupancyTracker::Segment>&& history) {
3586 Mutex::Autolock lock(mBufferingStatsMutex);
3587 auto& stats = mBufferingStats[layerName];
3588 for (const auto& segment : history) {
3589 if (!segment.usedThirdBuffer) {
3590 stats.twoBufferTime += segment.totalTime;
3591 }
3592 if (segment.occupancyAverage < 1.0f) {
3593 stats.doubleBufferedTime += segment.totalTime;
3594 } else if (segment.occupancyAverage < 2.0f) {
3595 stats.tripleBufferedTime += segment.totalTime;
3596 }
3597 ++stats.numSegments;
3598 stats.totalTime += segment.totalTime;
3599 }
3600}
3601
Brian Andersond6927fb2016-07-23 23:37:30 -07003602void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3603 result.appendFormat("Layer frame timestamps:\n");
3604
3605 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3606 const size_t count = currentLayers.size();
3607 for (size_t i=0 ; i<count ; i++) {
3608 currentLayers[i]->dumpFrameEvents(result);
3609 }
3610}
3611
Dan Stozae77c7662016-05-13 11:37:28 -07003612void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3613 result.append("Buffering stats:\n");
3614 result.append(" [Layer name] <Active time> <Two buffer> "
3615 "<Double buffered> <Triple buffered>\n");
3616 Mutex::Autolock lock(mBufferingStatsMutex);
3617 typedef std::tuple<std::string, float, float, float> BufferTuple;
3618 std::map<float, BufferTuple, std::greater<float>> sorted;
3619 for (const auto& statsPair : mBufferingStats) {
3620 const char* name = statsPair.first.c_str();
3621 const BufferingStats& stats = statsPair.second;
3622 if (stats.numSegments == 0) {
3623 continue;
3624 }
3625 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3626 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3627 stats.totalTime;
3628 float doubleBufferRatio = static_cast<float>(
3629 stats.doubleBufferedTime) / stats.totalTime;
3630 float tripleBufferRatio = static_cast<float>(
3631 stats.tripleBufferedTime) / stats.totalTime;
3632 sorted.insert({activeTime, {name, twoBufferRatio,
3633 doubleBufferRatio, tripleBufferRatio}});
3634 }
3635 for (const auto& sortedPair : sorted) {
3636 float activeTime = sortedPair.first;
3637 const BufferTuple& values = sortedPair.second;
3638 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3639 std::get<0>(values).c_str(), activeTime,
3640 std::get<1>(values), std::get<2>(values),
3641 std::get<3>(values));
3642 }
3643 result.append("\n");
3644}
3645
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003646void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3647 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
3648
3649 // TODO: print out if wide-color mode is active or not
3650
3651 for (size_t d = 0; d < mDisplays.size(); d++) {
3652 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3653 int32_t hwcId = displayDevice->getHwcDisplayId();
3654 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3655 continue;
3656 }
3657
3658 result.appendFormat("Display %d color modes:\n", hwcId);
3659 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3660 for (auto&& mode : modes) {
3661 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3662 }
3663
3664 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3665 result.appendFormat(" Current color mode: %s (%d)\n",
3666 decodeColorMode(currentMode).c_str(), currentMode);
3667 }
3668 result.append("\n");
3669}
3670
Mathias Agopian74d211a2013-04-22 16:55:35 +02003671void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3672 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003673{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003674 bool colorize = false;
3675 if (index < args.size()
3676 && (args[index] == String16("--color"))) {
3677 colorize = true;
3678 index++;
3679 }
3680
3681 Colorizer colorizer(colorize);
3682
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003683 // figure out if we're stuck somewhere
3684 const nsecs_t now = systemTime();
3685 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3686 const nsecs_t inTransaction(mDebugInTransaction);
3687 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3688 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3689
3690 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003691 * Dump library configuration.
3692 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003693
3694 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003695 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003696 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003697 appendSfConfigString(result);
3698 appendUiConfigString(result);
3699 appendGuiConfigString(result);
3700 result.append("\n");
3701
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003702 result.append("\nWide-Color information:\n");
3703 dumpWideColorInfo(result);
3704
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003705 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003706 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003707 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003708 result.append(SyncFeatures::getInstance().toString());
3709 result.append("\n");
3710
Dan Stoza9e56aa02015-11-02 13:00:03 -08003711 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3712
Andy McFadden41d67d72014-04-25 16:58:34 -07003713 colorizer.bold(result);
3714 result.append("DispSync configuration: ");
3715 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003716 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003717 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003718 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003719 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003720 result.append("\n");
3721
Dan Stozab90cf072015-03-05 11:05:59 -08003722 // Dump static screen stats
3723 result.append("\n");
3724 dumpStaticScreenStats(result);
3725 result.append("\n");
3726
Dan Stozae77c7662016-05-13 11:37:28 -07003727 dumpBufferingStats(result);
3728
Andy McFadden4803b742012-09-24 19:07:20 -07003729 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003730 * Dump the visible layer list
3731 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003732 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003733 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003734 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003735 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003736 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003737 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003738
3739 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003740 * Dump Display state
3741 */
3742
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003743 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003744 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003745 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003746 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3747 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003748 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003749 }
3750
3751 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003752 * Dump SurfaceFlinger global state
3753 */
3754
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003755 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003756 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003757 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003758
Mathias Agopian888c8222012-08-04 21:10:38 -07003759 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003760 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003761
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003762 colorizer.bold(result);
3763 result.appendFormat("EGL implementation : %s\n",
3764 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3765 colorizer.reset(result);
3766 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003767 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003768
Mathias Agopian875d8e12013-06-07 15:35:48 -07003769 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003770
Mathias Agopian42977342012-08-05 00:40:46 -07003771 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003772 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3773 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003774 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003775 " last eglSwapBuffers() time: %f us\n"
3776 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003777 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003778 " refresh-rate : %f fps\n"
3779 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003780 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003781 " gpu_to_cpu_unsupported : %d\n"
3782 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003783 mLastSwapBufferTime/1000.0,
3784 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003785 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003786 1e9 / activeConfig->getVsyncPeriod(),
3787 activeConfig->getDpiX(),
3788 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003789 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003790
Mathias Agopian74d211a2013-04-22 16:55:35 +02003791 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003792 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003793
Mathias Agopian74d211a2013-04-22 16:55:35 +02003794 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003795 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003796
3797 /*
3798 * VSYNC state
3799 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003800 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003801 result.append("\n");
3802
3803 /*
3804 * HWC layer minidump
3805 */
3806 for (size_t d = 0; d < mDisplays.size(); d++) {
3807 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3808 int32_t hwcId = displayDevice->getHwcDisplayId();
3809 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3810 continue;
3811 }
3812
3813 result.appendFormat("Display %d HWC layers:\n", hwcId);
3814 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003815 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003816 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003817 });
Dan Stozae22aec72016-08-01 13:20:59 -07003818 result.append("\n");
3819 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003820
3821 /*
3822 * Dump HWComposer state
3823 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003824 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003825 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003826 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003827 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003828 result.appendFormat(" h/w composer %s\n",
3829 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003830 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003831
3832 /*
3833 * Dump gralloc state
3834 */
3835 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3836 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07003837
3838 /*
3839 * Dump VrFlinger state if in use.
3840 */
3841 if (mVrFlingerRequestsDisplay && mVrFlinger) {
3842 result.append("VrFlinger state:\n");
3843 result.append(mVrFlinger->Dump().c_str());
3844 result.append("\n");
3845 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003846}
3847
Mathias Agopian13127d82013-03-05 17:47:11 -08003848const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003849SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003850 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003851 wp<IBinder> dpy;
3852 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3853 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3854 dpy = mDisplays.keyAt(i);
3855 break;
3856 }
3857 }
3858 if (dpy == NULL) {
3859 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3860 // Just use the primary display so we have something to return
3861 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3862 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003863 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003864}
3865
Keun young Park63f165f2012-08-31 10:53:36 -07003866bool SurfaceFlinger::startDdmConnection()
3867{
3868 void* libddmconnection_dso =
3869 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3870 if (!libddmconnection_dso) {
3871 return false;
3872 }
3873 void (*DdmConnection_start)(const char* name);
3874 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003875 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003876 if (!DdmConnection_start) {
3877 dlclose(libddmconnection_dso);
3878 return false;
3879 }
3880 (*DdmConnection_start)(getServiceName());
3881 return true;
3882}
3883
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003884status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003885 switch (code) {
3886 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003887 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003888 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003889 case CLEAR_ANIMATION_FRAME_STATS:
3890 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003891 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003892 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003893 {
3894 // codes that require permission check
3895 IPCThreadState* ipc = IPCThreadState::self();
3896 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003897 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003898 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003899 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003900 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003901 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003902 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003903 break;
3904 }
Robert Carr1db73f62016-12-21 12:58:51 -08003905 /*
3906 * Calling setTransactionState is safe, because you need to have been
3907 * granted a reference to Client* and Handle* to do anything with it.
3908 *
3909 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3910 */
3911 case SET_TRANSACTION_STATE:
3912 case CREATE_SCOPED_CONNECTION:
3913 {
3914 return OK;
3915 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003916 case CAPTURE_SCREEN:
3917 {
3918 // codes that require permission check
3919 IPCThreadState* ipc = IPCThreadState::self();
3920 const int pid = ipc->getCallingPid();
3921 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003922 if ((uid != AID_GRAPHICS) &&
3923 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003924 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003925 return PERMISSION_DENIED;
3926 }
3927 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003928 }
3929 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003930 return OK;
3931}
3932
3933status_t SurfaceFlinger::onTransact(
3934 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3935{
3936 status_t credentialCheck = CheckTransactCodeCredentials(code);
3937 if (credentialCheck != OK) {
3938 return credentialCheck;
3939 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003940
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003941 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3942 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003943 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07003944 IPCThreadState* ipc = IPCThreadState::self();
3945 const int uid = ipc->getCallingUid();
3946 if (CC_UNLIKELY(uid != AID_SYSTEM
3947 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003948 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003949 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003950 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003951 return PERMISSION_DENIED;
3952 }
3953 int n;
3954 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003955 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003956 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003957 return NO_ERROR;
3958 case 1002: // SHOW_UPDATES
3959 n = data.readInt32();
3960 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003961 invalidateHwcGeometry();
3962 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003963 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003964 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003965 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003966 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003967 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003968 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003969 setTransactionFlags(
3970 eTransactionNeeded|
3971 eDisplayTransactionNeeded|
3972 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003973 return NO_ERROR;
3974 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003975 case 1006:{ // send empty update
3976 signalRefresh();
3977 return NO_ERROR;
3978 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003979 case 1008: // toggle use of hw composer
3980 n = data.readInt32();
3981 mDebugDisableHWC = n ? 1 : 0;
3982 invalidateHwcGeometry();
3983 repaintEverything();
3984 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003985 case 1009: // toggle use of transform hint
3986 n = data.readInt32();
3987 mDebugDisableTransformHint = n ? 1 : 0;
3988 invalidateHwcGeometry();
3989 repaintEverything();
3990 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003991 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003992 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003993 reply->writeInt32(0);
3994 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003995 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003996 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003997 return NO_ERROR;
3998 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00003999 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004000 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004001 return NO_ERROR;
4002 }
4003 case 1014: {
4004 // daltonize
4005 n = data.readInt32();
4006 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004007 case 1:
4008 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4009 break;
4010 case 2:
4011 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4012 break;
4013 case 3:
4014 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4015 break;
4016 default:
4017 mDaltonizer.setType(ColorBlindnessType::None);
4018 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004019 }
4020 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004021 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004022 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004023 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004024 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004025 invalidateHwcGeometry();
4026 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004027 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004028 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004029 case 1015: {
4030 // apply a color matrix
4031 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004032 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004033 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004034 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004035 for (size_t j = 0; j < 4; j++) {
4036 mColorMatrix[i][j] = data.readFloat();
4037 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004038 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004039 } else {
4040 mColorMatrix = mat4();
4041 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004042
4043 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4044 // the division by w in the fragment shader
4045 float4 lastRow(transpose(mColorMatrix)[3]);
4046 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4047 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4048 }
4049
Alan Viverette9c5a3332013-09-12 20:04:35 -07004050 invalidateHwcGeometry();
4051 repaintEverything();
4052 return NO_ERROR;
4053 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004054 // This is an experimental interface
4055 // Needs to be shifted to proper binder interface when we productize
4056 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004057 n = data.readInt32();
4058 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004059 return NO_ERROR;
4060 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004061 case 1017: {
4062 n = data.readInt32();
4063 mForceFullDamage = static_cast<bool>(n);
4064 return NO_ERROR;
4065 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004066 case 1018: { // Modify Choreographer's phase offset
4067 n = data.readInt32();
4068 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4069 return NO_ERROR;
4070 }
4071 case 1019: { // Modify SurfaceFlinger's phase offset
4072 n = data.readInt32();
4073 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4074 return NO_ERROR;
4075 }
Irvel468051e2016-06-13 16:44:44 -07004076 case 1020: { // Layer updates interceptor
4077 n = data.readInt32();
4078 if (n) {
4079 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004080 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004081 }
4082 else{
4083 ALOGV("Interceptor disabled");
4084 mInterceptor.disable();
4085 }
4086 return NO_ERROR;
4087 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004088 case 1021: { // Disable HWC virtual displays
4089 n = data.readInt32();
4090 mUseHwcVirtualDisplays = !n;
4091 return NO_ERROR;
4092 }
Romain Guy0147a172017-06-01 13:53:56 -07004093 case 1022: { // Set saturation boost
4094 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4095
4096 invalidateHwcGeometry();
4097 repaintEverything();
4098 return NO_ERROR;
4099 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004100 }
4101 }
4102 return err;
4103}
4104
Mathias Agopian53331da2011-08-22 21:44:41 -07004105void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004106 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004107 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004108}
4109
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004110// Checks that the requested width and height are valid and updates them to the display dimensions
4111// if they are set to 0
4112static status_t updateDimensionsLocked(const sp<const DisplayDevice>& displayDevice,
4113 Transform::orientation_flags rotation,
4114 uint32_t* requestedWidth, uint32_t* requestedHeight) {
4115 // get screen geometry
4116 uint32_t displayWidth = displayDevice->getWidth();
4117 uint32_t displayHeight = displayDevice->getHeight();
Mathias Agopian9daa5c92010-10-12 16:05:48 -07004118
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004119 if (rotation & Transform::ROT_90) {
4120 std::swap(displayWidth, displayHeight);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004121 }
4122
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004123 if ((*requestedWidth > displayWidth) || (*requestedHeight > displayHeight)) {
4124 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4125 *requestedWidth, *requestedHeight, displayWidth, displayHeight);
4126 return BAD_VALUE;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004127 }
4128
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004129 if (*requestedWidth == 0) {
4130 *requestedWidth = displayWidth;
4131 }
4132 if (*requestedHeight == 0) {
4133 *requestedHeight = displayHeight;
4134 }
4135
4136 return NO_ERROR;
4137}
4138
4139// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4140class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004141public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004142 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4143 ~WindowDisconnector() {
4144 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004145 }
4146
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004147private:
4148 ANativeWindow* mWindow;
4149 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004150};
4151
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004152static status_t getWindowBuffer(ANativeWindow* window, uint32_t requestedWidth,
4153 uint32_t requestedHeight, bool hasWideColorDisplay,
4154 bool renderEngineUsesWideColor, ANativeWindowBuffer** outBuffer) {
4155 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4156 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4157
4158 int err = 0;
4159 err = native_window_set_buffers_dimensions(window, requestedWidth, requestedHeight);
4160 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
4161 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4162 err |= native_window_set_usage(window, usage);
4163
4164 if (hasWideColorDisplay) {
4165 err |= native_window_set_buffers_data_space(window,
4166 renderEngineUsesWideColor
4167 ? HAL_DATASPACE_DISPLAY_P3
4168 : HAL_DATASPACE_V0_SRGB);
4169 }
4170
4171 if (err != NO_ERROR) {
4172 return BAD_VALUE;
4173 }
4174
4175 /* TODO: Once we have the sync framework everywhere this can use
4176 * server-side waits on the fence that dequeueBuffer returns.
4177 */
4178 err = native_window_dequeue_buffer_and_wait(window, outBuffer);
4179 if (err != NO_ERROR) {
4180 return err;
4181 }
4182
4183 return NO_ERROR;
4184}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004185
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004186status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4187 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004188 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004189 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004190 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004191 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004192
4193 if (CC_UNLIKELY(display == 0))
4194 return BAD_VALUE;
4195
4196 if (CC_UNLIKELY(producer == 0))
4197 return BAD_VALUE;
4198
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004199 // if we have secure windows on this display, never allow the screen capture
4200 // unless the producer interface is local (i.e.: we can take a screenshot for
4201 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004202 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004203
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004204 // Convert to surfaceflinger's internal rotation type.
4205 Transform::orientation_flags rotationFlags;
4206 switch (rotation) {
4207 case ISurfaceComposer::eRotateNone:
4208 rotationFlags = Transform::ROT_0;
4209 break;
4210 case ISurfaceComposer::eRotate90:
4211 rotationFlags = Transform::ROT_90;
4212 break;
4213 case ISurfaceComposer::eRotate180:
4214 rotationFlags = Transform::ROT_180;
4215 break;
4216 case ISurfaceComposer::eRotate270:
4217 rotationFlags = Transform::ROT_270;
4218 break;
4219 default:
4220 rotationFlags = Transform::ROT_0;
4221 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
4222 break;
4223 }
4224
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004225 { // Autolock scope
4226 Mutex::Autolock lock(mStateLock);
4227 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
4228 updateDimensionsLocked(displayDevice, rotationFlags, &reqWidth, &reqHeight);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004229 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004230
4231 // create a surface (because we're a producer, and we need to
4232 // dequeue/queue a buffer)
4233 sp<Surface> surface = new Surface(producer, false);
4234
4235 // Put the screenshot Surface into async mode so that
4236 // Layer::headFenceHasSignaled will always return true and we'll latch the
4237 // first buffer regardless of whether or not its acquire fence has
4238 // signaled. This is needed to avoid a race condition in the rotation
4239 // animation. See b/30209608
4240 surface->setAsyncMode(true);
4241
4242 ANativeWindow* window = surface.get();
4243
4244 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4245 if (result != NO_ERROR) {
4246 return result;
4247 }
4248 WindowDisconnector disconnector(window, NATIVE_WINDOW_API_EGL);
4249
4250 ANativeWindowBuffer* buffer = nullptr;
4251 result = getWindowBuffer(window, reqWidth, reqHeight, hasWideColorDisplay,
4252 getRenderEngine().usesWideColor(), &buffer);
4253 if (result != NO_ERROR) {
4254 return result;
4255 }
4256
4257 // This mutex protects syncFd and captureResult for communication of the return values from the
4258 // main thread back to this Binder thread
4259 std::mutex captureMutex;
4260 std::condition_variable captureCondition;
4261 std::unique_lock<std::mutex> captureLock(captureMutex);
4262 int syncFd = -1;
4263 std::optional<status_t> captureResult;
4264
4265 sp<LambdaMessage> message = new LambdaMessage([&]() {
4266 // If there is a refresh pending, bug out early and tell the binder thread to try again
4267 // after the refresh.
4268 if (mRefreshPending) {
4269 ATRACE_NAME("Skipping screenshot for now");
4270 std::unique_lock<std::mutex> captureLock(captureMutex);
4271 captureResult = std::make_optional<status_t>(EAGAIN);
4272 captureCondition.notify_one();
4273 return;
4274 }
4275
4276 status_t result = NO_ERROR;
4277 int fd = -1;
4278 {
4279 Mutex::Autolock _l(mStateLock);
4280 sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4281 result = captureScreenImplLocked(device, buffer, sourceCrop, reqWidth, reqHeight,
4282 minLayerZ, maxLayerZ, useIdentityTransform,
4283 rotationFlags, isLocalScreenshot, &fd);
4284 }
4285
4286 {
4287 std::unique_lock<std::mutex> captureLock(captureMutex);
4288 syncFd = fd;
4289 captureResult = std::make_optional<status_t>(result);
4290 captureCondition.notify_one();
4291 }
4292 });
4293
4294 result = postMessageAsync(message);
4295 if (result == NO_ERROR) {
4296 captureCondition.wait(captureLock, [&]() { return captureResult; });
4297 while (*captureResult == EAGAIN) {
4298 captureResult.reset();
4299 result = postMessageAsync(message);
4300 if (result != NO_ERROR) {
4301 return result;
4302 }
4303 captureCondition.wait(captureLock, [&]() { return captureResult; });
4304 }
4305 result = *captureResult;
4306 }
4307
4308 if (result == NO_ERROR) {
4309 // queueBuffer takes ownership of syncFd
4310 result = window->queueBuffer(window, buffer, syncFd);
4311 }
4312
4313 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004314}
4315
Mathias Agopian180f10d2013-04-10 22:55:41 -07004316
4317void SurfaceFlinger::renderScreenImplLocked(
4318 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07004319 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004320 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004321 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07004322{
4323 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07004324 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004325
4326 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08004327 const int32_t hw_w = hw->getWidth();
4328 const int32_t hw_h = hw->getHeight();
4329 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07004330 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004331
Dan Stozac1879002014-05-22 15:59:05 -07004332 // if a default or invalid sourceCrop is passed in, set reasonable values
4333 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
4334 !sourceCrop.isValid()) {
4335 sourceCrop.setLeftTop(Point(0, 0));
4336 sourceCrop.setRightBottom(Point(hw_w, hw_h));
4337 }
4338
4339 // ensure that sourceCrop is inside screen
4340 if (sourceCrop.left < 0) {
4341 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4342 }
Dan Stozabe31f442014-06-11 11:20:54 -07004343 if (sourceCrop.right > hw_w) {
4344 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07004345 }
4346 if (sourceCrop.top < 0) {
4347 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4348 }
Dan Stozabe31f442014-06-11 11:20:54 -07004349 if (sourceCrop.bottom > hw_h) {
4350 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004351 }
4352
Romain Guy88d37dd2017-05-26 17:57:05 -07004353#ifdef USE_HWC2
4354 engine.setWideColor(hw->getWideColorSupport());
4355 engine.setColorMode(hw->getActiveColorMode());
4356#endif
4357
Mathias Agopian180f10d2013-04-10 22:55:41 -07004358 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004359 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004360
4361 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004362 engine.setViewportAndProjection(
4363 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004364 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004365
4366 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004367 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004368
Robert Carr1f0a16a2016-10-24 16:27:39 -07004369 // We loop through the first level of layers without traversing,
4370 // as we need to interpret min/max layer Z in the top level Z space.
4371 for (const auto& layer : mDrawingState.layersSortedByZ) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07004372 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004373 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004374 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004375 const Layer::State& state(layer->getDrawingState());
4376 if (state.z < minLayerZ || state.z > maxLayerZ) {
4377 continue;
4378 }
Dan Stoza412903f2017-04-27 13:42:17 -07004379 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004380 if (!layer->isVisible()) {
4381 return;
4382 }
4383 if (filtering) layer->setFiltering(true);
4384 layer->draw(hw, useIdentityTransform);
4385 if (filtering) layer->setFiltering(false);
4386 });
4387 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004388
Mathias Agopian931bda12013-08-28 18:11:46 -07004389 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004390}
4391
Dan Stozaabcda352017-06-01 14:37:39 -07004392// A simple RAII class that holds an EGLImage and destroys it either:
4393// a) When the destroy() method is called
4394// b) When the object goes out of scope
4395class ImageHolder {
4396public:
4397 ImageHolder(EGLDisplay display, EGLImageKHR image) : mDisplay(display), mImage(image) {}
4398 ~ImageHolder() { destroy(); }
4399
4400 void destroy() {
4401 if (mImage != EGL_NO_IMAGE_KHR) {
4402 eglDestroyImageKHR(mDisplay, mImage);
4403 mImage = EGL_NO_IMAGE_KHR;
4404 }
4405 }
4406
4407private:
4408 const EGLDisplay mDisplay;
4409 EGLImageKHR mImage;
4410};
4411
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004412status_t SurfaceFlinger::captureScreenImplLocked(const sp<const DisplayDevice>& hw,
4413 ANativeWindowBuffer* buffer, Rect sourceCrop,
4414 uint32_t reqWidth, uint32_t reqHeight,
4415 int32_t minLayerZ, int32_t maxLayerZ,
4416 bool useIdentityTransform,
4417 Transform::orientation_flags rotation,
4418 bool isLocalScreenshot, int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004419 ATRACE_CALL();
4420
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004421 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004422 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004423 const Layer::State& state(layer->getDrawingState());
Chia-I Wufc0b9112017-08-07 15:27:49 -07004424 if (!layer->belongsToDisplay(hw->getLayerStack(), false) ||
Robert Carr1f0a16a2016-10-24 16:27:39 -07004425 (state.z < minLayerZ || state.z > maxLayerZ)) {
4426 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004427 }
Dan Stoza412903f2017-04-27 13:42:17 -07004428 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer *layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004429 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4430 layer->isSecure());
4431 });
4432 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004433
4434 if (!isLocalScreenshot && secureLayerIsVisible) {
4435 ALOGW("FB is protected: PERMISSION_DENIED");
4436 return PERMISSION_DENIED;
4437 }
4438
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004439 int syncFd = -1;
4440 // create an EGLImage from the buffer so we can later
4441 // turn it into a texture
4442 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4443 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4444 if (image == EGL_NO_IMAGE_KHR) {
4445 return BAD_VALUE;
4446 }
4447
Dan Stozaabcda352017-06-01 14:37:39 -07004448 // This will automatically destroy the image if we return before calling its destroy method
4449 ImageHolder imageHolder(mEGLDisplay, image);
4450
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004451 // this binds the given EGLImage as a framebuffer for the
4452 // duration of this scope.
4453 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
Dan Stozaabcda352017-06-01 14:37:39 -07004454 if (imageBond.getStatus() != NO_ERROR) {
4455 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004456 return INVALID_OPERATION;
4457 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004458
Dan Stozaabcda352017-06-01 14:37:39 -07004459 // this will in fact render into our dequeued buffer
4460 // via an FBO, which means we didn't have to create
4461 // an EGLSurface and therefore we're not
4462 // dependent on the context's EGLConfig.
4463 renderScreenImplLocked(
4464 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4465 useIdentityTransform, rotation);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004466
Dan Stozaabcda352017-06-01 14:37:39 -07004467 // Attempt to create a sync khr object that can produce a sync point. If that
4468 // isn't available, create a non-dupable sync object in the fallback path and
4469 // wait on it directly.
4470 EGLSyncKHR sync = EGL_NO_SYNC_KHR;
4471 if (!DEBUG_SCREENSHOTS) {
4472 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
4473 // native fence fd will not be populated until flush() is done.
4474 getRenderEngine().flush();
4475 }
4476
4477 if (sync != EGL_NO_SYNC_KHR) {
4478 // get the sync fd
4479 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4480 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4481 ALOGW("captureScreen: failed to dup sync khr object");
4482 syncFd = -1;
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004483 }
Dan Stozaabcda352017-06-01 14:37:39 -07004484 eglDestroySyncKHR(mEGLDisplay, sync);
4485 } else {
4486 // fallback path
4487 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004488 if (sync != EGL_NO_SYNC_KHR) {
Dan Stozaabcda352017-06-01 14:37:39 -07004489 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4490 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4491 EGLint eglErr = eglGetError();
4492 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4493 ALOGW("captureScreen: fence wait timed out");
4494 } else {
4495 ALOGW_IF(eglErr != EGL_SUCCESS,
4496 "captureScreen: error waiting on EGL fence: %#x", eglErr);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004497 }
4498 eglDestroySyncKHR(mEGLDisplay, sync);
4499 } else {
Dan Stozaabcda352017-06-01 14:37:39 -07004500 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004501 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004502 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004503 *outSyncFd = syncFd;
Dan Stozaabcda352017-06-01 14:37:39 -07004504
4505 if (DEBUG_SCREENSHOTS) {
4506 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4507 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4508 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4509 hw, minLayerZ, maxLayerZ);
4510 delete [] pixels;
4511 }
4512
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004513 // destroy our image
Dan Stozaabcda352017-06-01 14:37:39 -07004514 imageHolder.destroy();
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004515
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004516 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004517}
4518
Mathias Agopiand5556842013-09-19 17:08:37 -07004519void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004520 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004521 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004522 for (size_t y=0 ; y<h ; y++) {
4523 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4524 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004525 if (p[x] != 0xFF000000) return;
4526 }
4527 }
4528 ALOGE("*** we just took a black screenshot ***\n"
4529 "requested minz=%d, maxz=%d, layerStack=%d",
4530 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004531
Robert Carr2047fae2016-11-28 14:09:09 -08004532 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004533 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004534 const Layer::State& state(layer->getDrawingState());
Chia-I Wuab0c3192017-08-01 11:29:00 -07004535 if (layer->belongsToDisplay(hw->getLayerStack(), false) && state.z >= minLayerZ &&
Robert Carr1f0a16a2016-10-24 16:27:39 -07004536 state.z <= maxLayerZ) {
Dan Stoza412903f2017-04-27 13:42:17 -07004537 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004538 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4539 layer->isVisible() ? '+' : '-',
4540 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004541 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004542 i++;
4543 });
4544 }
4545 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004546 }
4547}
4548
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004549// ---------------------------------------------------------------------------
4550
Dan Stoza412903f2017-04-27 13:42:17 -07004551void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4552 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004553}
4554
Dan Stoza412903f2017-04-27 13:42:17 -07004555void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4556 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004557}
4558
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004559}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004560
4561
4562#if defined(__gl_h_)
4563#error "don't include gl/gl.h in this file"
4564#endif
4565
4566#if defined(__gl2_h_)
4567#error "don't include gl2/gl2.h in this file"
4568#endif