blob: 0d934671255798e4c639898944fd95a1a59bdc9a [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>
Kalle Raitaa099a242017-01-11 11:17:29 -080049#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080050#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070051
52#include <ui/GraphicBufferAllocator.h>
53#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070054#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080055
Mathias Agopiancde87a32012-09-13 14:09:01 -070056#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080057#include <utils/String8.h>
58#include <utils/String16.h>
59#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070060#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080061#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062
Mathias Agopian921e6ac2012-07-23 23:11:29 -070063#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070064#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065
Mathias Agopian3e25fd82013-04-22 17:52:16 +020066#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080067#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020068#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080069#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070070#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070071#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070072#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080073#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076#include "LayerDim.h"
Robert Carr1db73f62016-12-21 12:58:51 -080077#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Steven Thomasb02664d2017-07-26 18:48:28 -070080#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070081#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070082#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070083#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084
Mathias Agopianff2ed702013-09-01 21:36:12 -070085#include "Effects/Daltonizer.h"
86
Mathias Agopian875d8e12013-06-07 15:35:48 -070087#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070088#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070089
Jiyong Park4b20c2e2017-01-14 19:45:11 +090090#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090091#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090092
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080093#define DISPLAY_COUNT 1
94
Mathias Agopianfee2b462013-07-03 12:34:01 -070095/*
96 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
97 * black pixels.
98 */
99#define DEBUG_SCREENSHOTS false
100
Mathias Agopianca088332013-03-28 17:44:13 -0700101EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
102
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800103namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700104
Jaesoo Lee43518572017-01-23 19:03:16 +0900105using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900106using namespace android::hardware::configstore::V1_0;
107
Steven Thomasb02664d2017-07-26 18:48:28 -0700108namespace {
109class ConditionalLock {
110public:
111 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
112 if (lock) {
113 mMutex.lock();
114 }
115 }
116 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
117private:
118 Mutex& mMutex;
119 bool mLocked;
120};
121} // namespace anonymous
122
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800123// ---------------------------------------------------------------------------
124
Mathias Agopian99b49842011-06-27 16:05:52 -0700125const String16 sHardwareTest("android.permission.HARDWARE_TEST");
126const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
127const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
128const String16 sDump("android.permission.DUMP");
129
130// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800131int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
132int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700133bool SurfaceFlinger::useContextPriority;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700134int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700135bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800136uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800137bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800138bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800139int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600140bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700141
Kalle Raitaa099a242017-01-11 11:17:29 -0800142
143std::string getHwcServiceName() {
144 char value[PROPERTY_VALUE_MAX] = {};
145 property_get("debug.sf.hwc_service_name", value, "default");
146 ALOGI("Using HWComposer service: '%s'", value);
147 return std::string(value);
148}
149
150bool useTrebleTestingOverride() {
151 char value[PROPERTY_VALUE_MAX] = {};
152 property_get("debug.sf.treble_testing_override", value, "false");
153 ALOGI("Treble testing override: '%s'", value);
154 return std::string(value) == "true";
155}
156
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800157SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700158 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800159 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700160 mTransactionPending(false),
161 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700162 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700163 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700164 mRepaintEverything(0),
Kalle Raitaa099a242017-01-11 11:17:29 -0800165 mHwcServiceName(getHwcServiceName()),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800166 mRenderEngine(nullptr),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800167 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800168 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800169 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800170 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800171 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800172 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700173 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700174 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700175 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700176 mDebugInSwapBuffers(0),
177 mLastSwapBufferTime(0),
178 mDebugInTransaction(0),
179 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700180 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700181 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800182 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000183 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700184 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700185 mHWVsyncAvailable(false),
Romain Guya9638732017-06-01 12:05:21 -0700186 mHasColorMatrix(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800187 mHasPoweredOff(false),
188 mFrameBuckets(),
189 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700190 mLastSwapTime(0),
Steven Thomas050b2c82017-03-06 11:45:16 -0800191 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700192 mVrFlingerRequestsDisplay(false),
193 mMainThreadId(std::this_thread::get_id()),
194 mComposerSequenceId(0)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800195{
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800196 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800197
198 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
199 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
200
201 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
202 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
203
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800204 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
205 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800206
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700207 useContextPriority = getBool< ISurfaceFlingerConfigs,
208 &ISurfaceFlingerConfigs::useContextPriority>(false);
209
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700210 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
211 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
212
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700213 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
214 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
215
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800216 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
217 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
218
Steven Thomas050b2c82017-03-06 11:45:16 -0800219 // Vr flinger is only enabled on Daydream ready devices.
220 useVrFlinger = getBool< ISurfaceFlingerConfigs,
221 &ISurfaceFlingerConfigs::useVrFlinger>(false);
222
Fabien Sanglard1971b632017-03-10 14:50:03 -0800223 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
224 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
225
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600226 hasWideColorDisplay =
227 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
228
Saurabh Shahf4174532017-07-13 10:45:07 -0700229 mPrimaryDispSync.init(hasSyncFramework, dispSyncPresentTimeOffset);
230
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800231 // debugging stuff...
232 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700233
Mathias Agopianb4b17302013-03-20 18:36:41 -0700234 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700235 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700236
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800237 property_get("debug.sf.showupdates", value, "0");
238 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700239
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700240 property_get("debug.sf.ddms", value, "0");
241 mDebugDDMS = atoi(value);
242 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700243 if (!startDdmConnection()) {
244 // start failed, and DDMS debugging not enabled
245 mDebugDDMS = 0;
246 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700247 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700248 ALOGI_IF(mDebugRegion, "showupdates enabled");
249 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700250
251 property_get("debug.sf.disable_backpressure", value, "0");
252 mPropagateBackpressure = !atoi(value);
253 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700254
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800255 property_get("debug.sf.enable_hwc_vds", value, "0");
256 mUseHwcVirtualDisplays = atoi(value);
257 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800258
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800259 property_get("ro.sf.disable_triple_buffer", value, "1");
260 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800261 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700262
Romain Guy11d63f42017-07-20 12:47:14 -0700263 // We should be reading 'persist.sys.sf.color_saturation' here
264 // but since /data may be encrypted, we need to wait until after vold
265 // comes online to attempt to read the property. The property is
266 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800267
268 if (useTrebleTestingOverride()) {
269 // Without the override SurfaceFlinger cannot connect to HIDL
270 // services that are not listed in the manifests. Considered
271 // deriving the setting from the set service name, but it
272 // would be brittle if the name that's not 'default' is used
273 // for production purposes later on.
274 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
275 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800276}
277
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800278void SurfaceFlinger::onFirstRef()
279{
280 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800281}
282
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800283SurfaceFlinger::~SurfaceFlinger()
284{
Mathias Agopiana4912602012-07-12 14:25:33 -0700285 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
286 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
287 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800288}
289
Dan Stozac7014012014-02-14 15:03:43 -0800290void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800291{
292 // the window manager died on us. prepare its eulogy.
293
Andy McFadden13a082e2012-08-24 10:16:42 -0700294 // restore initial conditions (default device unblank, etc)
295 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800296
297 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700298 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800299}
300
Robert Carr1db73f62016-12-21 12:58:51 -0800301static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700302 status_t err = client->initCheck();
303 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800304 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800305 }
Robert Carr1db73f62016-12-21 12:58:51 -0800306 return nullptr;
307}
308
309sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
310 return initClient(new Client(this));
311}
312
313sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
314 const sp<IGraphicBufferProducer>& gbp) {
315 if (authenticateSurfaceTexture(gbp) == false) {
316 return nullptr;
317 }
318 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
319 if (layer == nullptr) {
320 return nullptr;
321 }
322
323 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800324}
325
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700326sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
327 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700328{
329 class DisplayToken : public BBinder {
330 sp<SurfaceFlinger> flinger;
331 virtual ~DisplayToken() {
332 // no more references, this display must be terminated
333 Mutex::Autolock _l(flinger->mStateLock);
334 flinger->mCurrentState.displays.removeItem(this);
335 flinger->setTransactionFlags(eDisplayTransactionNeeded);
336 }
337 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700338 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700339 : flinger(flinger) {
340 }
341 };
342
343 sp<BBinder> token = new DisplayToken(this);
344
345 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700346 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700347 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700348 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700349 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700350 return token;
351}
352
Jesse Hall6c913be2013-08-08 12:15:49 -0700353void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
354 Mutex::Autolock _l(mStateLock);
355
356 ssize_t idx = mCurrentState.displays.indexOfKey(display);
357 if (idx < 0) {
358 ALOGW("destroyDisplay: invalid display token");
359 return;
360 }
361
362 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
363 if (!info.isVirtualDisplay()) {
364 ALOGE("destroyDisplay called for non-virtual display");
365 return;
366 }
Irvelffc9efc2016-07-27 15:16:37 -0700367 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700368 mCurrentState.displays.removeItemsAt(idx);
369 setTransactionFlags(eDisplayTransactionNeeded);
370}
371
Jesse Hall692c7232012-11-08 15:41:56 -0800372void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800373 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800374 ALOGW_IF(mBuiltinDisplays[type],
375 "Overwriting display token for display type %d", type);
376 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800377 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700378 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800379 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700380 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800381}
382
Mathias Agopiane57f2922012-08-09 16:29:12 -0700383sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700384 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700385 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
386 return NULL;
387 }
Jesse Hall692c7232012-11-08 15:41:56 -0800388 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700389}
390
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800391void SurfaceFlinger::bootFinished()
392{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700393 if (mStartPropertySetThread->join() != NO_ERROR) {
394 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800395 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800396 const nsecs_t now = systemTime();
397 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000398 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700399
400 // wait patiently for the window manager death
401 const String16 name("window");
402 sp<IBinder> window(defaultServiceManager()->getService(name));
403 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700404 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700405 }
406
Steven Thomas050b2c82017-03-06 11:45:16 -0800407 if (mVrFlinger) {
408 mVrFlinger->OnBootFinished();
409 }
410
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700411 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700412 // formerly we would just kill the process, but we now ask it to exit so it
413 // can choose where to stop the animation.
414 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700415
416 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
417 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
418 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700419
Romain Guyc53d3552017-07-20 18:49:46 -0700420 sp<LambdaMessage> bootFinished = new LambdaMessage([&]() {
421 mBootFinished = true;
422
Romain Guy11d63f42017-07-20 12:47:14 -0700423 readPersistentProperties();
Romain Guyc53d3552017-07-20 18:49:46 -0700424
425#ifdef USE_HWC2
426 sp<DisplayDevice> hw(getDisplayDevice(mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
427 if (hw->getWideColorSupport()) {
Courtney Goeltzenleuchter79d27242017-07-13 17:54:01 -0600428 hw->setCompositionDataSpace(HAL_DATASPACE_V0_SRGB);
Romain Guyc53d3552017-07-20 18:49:46 -0700429 setActiveColorModeInternal(hw, HAL_COLOR_MODE_SRGB);
430 }
431#endif
Romain Guy11d63f42017-07-20 12:47:14 -0700432 });
Romain Guyc53d3552017-07-20 18:49:46 -0700433 postMessageAsync(bootFinished);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800434}
435
Mathias Agopian3f844832013-08-07 21:24:32 -0700436void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700437 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700438 RenderEngine& engine;
439 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700440 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700441 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
442 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700443 }
444 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700445 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700446 return true;
447 }
448 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700449 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700450}
451
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700452class DispSyncSource : public VSyncSource, private DispSync::Callback {
453public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700454 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000455 const char* name) :
456 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700457 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700458 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000459 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
460 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700461 mDispSync(dispSync),
462 mCallbackMutex(),
463 mCallback(),
464 mVsyncMutex(),
465 mPhaseOffset(phaseOffset),
466 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700467
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700468 virtual ~DispSyncSource() {}
469
470 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700471 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700472 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000473 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700474 static_cast<DispSync::Callback*>(this));
475 if (err != NO_ERROR) {
476 ALOGE("error registering vsync callback: %s (%d)",
477 strerror(-err), err);
478 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700479 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700480 } else {
481 status_t err = mDispSync->removeEventListener(
482 static_cast<DispSync::Callback*>(this));
483 if (err != NO_ERROR) {
484 ALOGE("error unregistering vsync callback: %s (%d)",
485 strerror(-err), err);
486 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700487 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700488 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700489 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700490 }
491
492 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700493 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700494 mCallback = callback;
495 }
496
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700497 virtual void setPhaseOffset(nsecs_t phaseOffset) {
498 Mutex::Autolock lock(mVsyncMutex);
499
500 // Normalize phaseOffset to [0, period)
501 auto period = mDispSync->getPeriod();
502 phaseOffset %= period;
503 if (phaseOffset < 0) {
504 // If we're here, then phaseOffset is in (-period, 0). After this
505 // operation, it will be in (0, period)
506 phaseOffset += period;
507 }
508 mPhaseOffset = phaseOffset;
509
510 // If we're not enabled, we don't need to mess with the listeners
511 if (!mEnabled) {
512 return;
513 }
514
515 // Remove the listener with the old offset
516 status_t err = mDispSync->removeEventListener(
517 static_cast<DispSync::Callback*>(this));
518 if (err != NO_ERROR) {
519 ALOGE("error unregistering vsync callback: %s (%d)",
520 strerror(-err), err);
521 }
522
523 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000524 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700525 static_cast<DispSync::Callback*>(this));
526 if (err != NO_ERROR) {
527 ALOGE("error registering vsync callback: %s (%d)",
528 strerror(-err), err);
529 }
530 }
531
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700532private:
533 virtual void onDispSyncEvent(nsecs_t when) {
534 sp<VSyncSource::Callback> callback;
535 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700536 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700537 callback = mCallback;
538
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700539 if (mTraceVsync) {
540 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700541 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700542 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700543 }
544
545 if (callback != NULL) {
546 callback->onVSyncEvent(when);
547 }
548 }
549
Tim Murray4a4e4a22016-04-19 16:29:23 +0000550 const char* const mName;
551
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700552 int mValue;
553
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700554 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700555 const String8 mVsyncOnLabel;
556 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700557
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700558 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700559
560 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700561 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700562
563 Mutex mVsyncMutex; // Protects the following
564 nsecs_t mPhaseOffset;
565 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700566};
567
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700568class InjectVSyncSource : public VSyncSource {
569public:
570 InjectVSyncSource() {}
571
572 virtual ~InjectVSyncSource() {}
573
574 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
575 std::lock_guard<std::mutex> lock(mCallbackMutex);
576 mCallback = callback;
577 }
578
579 virtual void onInjectSyncEvent(nsecs_t when) {
580 std::lock_guard<std::mutex> lock(mCallbackMutex);
581 mCallback->onVSyncEvent(when);
582 }
583
584 virtual void setVSyncEnabled(bool) {}
585 virtual void setPhaseOffset(nsecs_t) {}
586
587private:
588 std::mutex mCallbackMutex; // Protects the following
589 sp<VSyncSource::Callback> mCallback;
590};
591
Wei Wangf9b05ee2017-07-19 20:59:39 -0700592// Do not call property_set on main thread which will be blocked by init
593// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700594void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700595 ALOGI( "SurfaceFlinger's main thread ready to run. "
596 "Initializing graphics H/W...");
597
Romain Guyc53d3552017-07-20 18:49:46 -0700598 ALOGI("Phase offset NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900599
Steven Thomasb02664d2017-07-26 18:48:28 -0700600 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800601
Steven Thomasb02664d2017-07-26 18:48:28 -0700602 // initialize EGL for the default display
603 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
604 eglInitialize(mEGLDisplay, NULL, NULL);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800605
Steven Thomasb02664d2017-07-26 18:48:28 -0700606 // start the EventThread
607 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
608 vsyncPhaseOffsetNs, true, "app");
609 mEventThread = new EventThread(vsyncSrc, *this, false);
610 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
611 sfVsyncPhaseOffsetNs, true, "sf");
612 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
613 mEventQueue.setEventThread(mSFEventThread);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800614
Steven Thomasb02664d2017-07-26 18:48:28 -0700615 // set EventThread and SFEventThread to SCHED_FIFO to minimize jitter
616 struct sched_param param = {0};
617 param.sched_priority = 2;
618 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
619 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
620 }
621 if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
622 ALOGE("Couldn't set SCHED_FIFO for EventThread");
Dan Stoza9e56aa02015-11-02 13:00:03 -0800623 }
624
Steven Thomasb02664d2017-07-26 18:48:28 -0700625 // Get a RenderEngine for the given display / config (can't fail)
626 mRenderEngine = RenderEngine::create(mEGLDisplay,
627 HAL_PIXEL_FORMAT_RGBA_8888,
628 hasWideColorDisplay ? RenderEngine::WIDE_COLOR_SUPPORT : 0);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800629
Steven Thomasb02664d2017-07-26 18:48:28 -0700630 // retrieve the EGL context that was selected/created
631 mEGLContext = mRenderEngine->getEGLContext();
632
633 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
634 "couldn't create EGLContext");
635
636 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
637 "Starting with vr flinger active is not currently supported.");
638 mHwc.reset(new HWComposer(mHwcServiceName));
639 mHwc->registerCallback(this, mComposerSequenceId);
Jesse Hall692c7232012-11-08 15:41:56 -0800640
Steven Thomas050b2c82017-03-06 11:45:16 -0800641 if (useVrFlinger) {
642 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700643 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
Steven Thomas050b2c82017-03-06 11:45:16 -0800644 mVrFlingerRequestsDisplay = requestDisplay;
645 signalTransaction();
646 };
647 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
648 vrFlingerRequestDisplayCallback);
649 if (!mVrFlinger) {
650 ALOGE("Failed to start vrflinger");
651 }
652 }
653
Jamie Gennisd1700752013-10-14 12:22:52 -0700654 mEventControlThread = new EventControlThread(this);
655 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
656
Mathias Agopian92a979a2012-08-02 18:32:23 -0700657 // initialize our drawing state
658 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700659
Andy McFadden13a082e2012-08-24 10:16:42 -0700660 // set initial conditions (e.g. unblank default device)
661 initializeDisplays();
662
Dan Stoza4e637772016-07-28 13:31:51 -0700663 mRenderEngine->primeCache();
664
Wei Wangf9b05ee2017-07-19 20:59:39 -0700665 // Inform native graphics APIs whether the present timestamp is supported:
666 if (getHwComposer().hasCapability(
667 HWC2::Capability::PresentFenceIsNotReliable)) {
668 mStartPropertySetThread = new StartPropertySetThread(false);
669 } else {
670 mStartPropertySetThread = new StartPropertySetThread(true);
671 }
672
673 if (mStartPropertySetThread->Start() != NO_ERROR) {
674 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800675 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800676
Dan Stoza9e56aa02015-11-02 13:00:03 -0800677 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700678}
679
Romain Guy11d63f42017-07-20 12:47:14 -0700680void SurfaceFlinger::readPersistentProperties() {
681 char value[PROPERTY_VALUE_MAX];
682
683 property_get("persist.sys.sf.color_saturation", value, "1.0");
684 mSaturation = atof(value);
685 ALOGV("Saturation is set to %.2f", mSaturation);
686}
687
Mathias Agopiana67e4182012-06-19 17:26:12 -0700688void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800689 // Start boot animation service by setting a property mailbox
690 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700691 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800692 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700693 if (mStartPropertySetThread->join() != NO_ERROR) {
694 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800695 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700696}
697
Mathias Agopian875d8e12013-06-07 15:35:48 -0700698size_t SurfaceFlinger::getMaxTextureSize() const {
699 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700700}
701
Mathias Agopian875d8e12013-06-07 15:35:48 -0700702size_t SurfaceFlinger::getMaxViewportDims() const {
703 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700704}
705
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800706// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800707
Jamie Gennis582270d2011-08-17 18:19:00 -0700708bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800709 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800710 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800711 return authenticateSurfaceTextureLocked(bufferProducer);
712}
713
714bool SurfaceFlinger::authenticateSurfaceTextureLocked(
715 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800716 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700717 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800718}
719
Brian Anderson6b376712017-04-04 10:51:39 -0700720status_t SurfaceFlinger::getSupportedFrameTimestamps(
721 std::vector<FrameEvent>* outSupported) const {
722 *outSupported = {
723 FrameEvent::REQUESTED_PRESENT,
724 FrameEvent::ACQUIRE,
725 FrameEvent::LATCH,
726 FrameEvent::FIRST_REFRESH_START,
727 FrameEvent::LAST_REFRESH_START,
728 FrameEvent::GPU_COMPOSITION_DONE,
729 FrameEvent::DEQUEUE_READY,
730 FrameEvent::RELEASE,
731 };
732 if (!getHwComposer().hasCapability(
733 HWC2::Capability::PresentFenceIsNotReliable)) {
734 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
735 }
736 return NO_ERROR;
737}
738
Dan Stoza7f7da322014-05-02 15:26:25 -0700739status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
740 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700741 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700742 return BAD_VALUE;
743 }
744
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500745 if (!display.get())
746 return NAME_NOT_FOUND;
747
Jesse Hall692c7232012-11-08 15:41:56 -0800748 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700749 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800750 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700751 type = i;
752 break;
753 }
754 }
755
756 if (type < 0) {
757 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700758 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700759
Mathias Agopian8b736f12012-08-13 17:54:26 -0700760 // TODO: Not sure if display density should handled by SF any longer
761 class Density {
762 static int getDensityFromProperty(char const* propName) {
763 char property[PROPERTY_VALUE_MAX];
764 int density = 0;
765 if (property_get(propName, property, NULL) > 0) {
766 density = atoi(property);
767 }
768 return density;
769 }
770 public:
771 static int getEmuDensity() {
772 return getDensityFromProperty("qemu.sf.lcd_density"); }
773 static int getBuildDensity() {
774 return getDensityFromProperty("ro.sf.lcd_density"); }
775 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700776
Dan Stoza7f7da322014-05-02 15:26:25 -0700777 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700778
Dan Stoza9e56aa02015-11-02 13:00:03 -0800779 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700780 DisplayInfo info = DisplayInfo();
781
Dan Stoza9e56aa02015-11-02 13:00:03 -0800782 float xdpi = hwConfig->getDpiX();
783 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700784
785 if (type == DisplayDevice::DISPLAY_PRIMARY) {
786 // The density of the device is provided by a build property
787 float density = Density::getBuildDensity() / 160.0f;
788 if (density == 0) {
789 // the build doesn't provide a density -- this is wrong!
790 // use xdpi instead
791 ALOGE("ro.sf.lcd_density must be defined as a build property");
792 density = xdpi / 160.0f;
793 }
794 if (Density::getEmuDensity()) {
795 // if "qemu.sf.lcd_density" is specified, it overrides everything
796 xdpi = ydpi = density = Density::getEmuDensity();
797 density /= 160.0f;
798 }
799 info.density = density;
800
801 // TODO: this needs to go away (currently needed only by webkit)
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000802 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
803 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700804 } else {
805 // TODO: where should this value come from?
806 static const int TV_DENSITY = 213;
807 info.density = TV_DENSITY / 160.0f;
808 info.orientation = 0;
809 }
810
Dan Stoza9e56aa02015-11-02 13:00:03 -0800811 info.w = hwConfig->getWidth();
812 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700813 info.xdpi = xdpi;
814 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800815 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900816 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800817
Andy McFadden91b2ca82014-06-13 14:04:23 -0700818 // This is how far in advance a buffer must be queued for
819 // presentation at a given time. If you want a buffer to appear
820 // on the screen at time N, you must submit the buffer before
821 // (N - presentationDeadline).
822 //
823 // Normally it's one full refresh period (to give SF a chance to
824 // latch the buffer), but this can be reduced by configuring a
825 // DispSync offset. Any additional delays introduced by the hardware
826 // composer or panel must be accounted for here.
827 //
828 // We add an additional 1ms to allow for processing time and
829 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800830 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800831 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700832
833 // All non-virtual displays are currently considered secure.
834 info.secure = true;
835
Michael Wright28f24d02016-07-12 13:30:53 -0700836 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700837 }
838
Dan Stoza7f7da322014-05-02 15:26:25 -0700839 return NO_ERROR;
840}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700841
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800842status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700843 DisplayStatInfo* stats) {
844 if (stats == NULL) {
845 return BAD_VALUE;
846 }
847
848 // FIXME for now we always return stats for the primary display
849 memset(stats, 0, sizeof(*stats));
850 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
851 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
852 return NO_ERROR;
853}
854
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700855int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800856 if (display == NULL) {
857 ALOGE("%s : display is NULL", __func__);
858 return BAD_VALUE;
859 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700860
861 sp<const DisplayDevice> device(getDisplayDevice(display));
Dan Stoza24a42e92015-03-09 10:04:11 -0700862 if (device != NULL) {
863 return device->getActiveConfig();
864 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700865
Dan Stoza24a42e92015-03-09 10:04:11 -0700866 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700867}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700868
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700869void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
870 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
871 this);
872 int32_t type = hw->getDisplayType();
873 int currentMode = hw->getActiveConfig();
874
875 if (mode == currentMode) {
876 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
877 return;
878 }
879
880 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
881 ALOGW("Trying to set config for virtual display");
882 return;
883 }
884
885 hw->setActiveConfig(mode);
886 getHwComposer().setActiveConfig(type, mode);
887}
888
889status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
890 class MessageSetActiveConfig: public MessageBase {
891 SurfaceFlinger& mFlinger;
892 sp<IBinder> mDisplay;
893 int mMode;
894 public:
895 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
896 int mode) :
897 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
898 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700899 Vector<DisplayInfo> configs;
900 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700901 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700902 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700903 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700904 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700905 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700906 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
907 if (hw == NULL) {
908 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700909 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700910 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
911 ALOGW("Attempt to set active config = %d for virtual display",
912 mMode);
913 } else {
914 mFlinger.setActiveConfigInternal(hw, mMode);
915 }
916 return true;
917 }
918 };
919 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
920 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700921 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700922}
Michael Wright28f24d02016-07-12 13:30:53 -0700923status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
924 Vector<android_color_mode_t>* outColorModes) {
925 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
926 return BAD_VALUE;
927 }
928
929 if (!display.get()) {
930 return NAME_NOT_FOUND;
931 }
932
933 int32_t type = NAME_NOT_FOUND;
934 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
935 if (display == mBuiltinDisplays[i]) {
936 type = i;
937 break;
938 }
939 }
940
941 if (type < 0) {
942 return type;
943 }
944
945 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
946 outColorModes->clear();
947 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
948
949 return NO_ERROR;
950}
951
952android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700953 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700954 if (device != nullptr) {
955 return device->getActiveColorMode();
956 }
957 return static_cast<android_color_mode_t>(BAD_VALUE);
958}
959
960void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
961 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700962 int32_t type = hw->getDisplayType();
963 android_color_mode_t currentMode = hw->getActiveColorMode();
964
965 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700966 return;
967 }
968
969 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
970 ALOGW("Trying to set config for virtual display");
971 return;
972 }
973
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600974 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
975 hw->getDisplayType());
976
Michael Wright28f24d02016-07-12 13:30:53 -0700977 hw->setActiveColorMode(mode);
978 getHwComposer().setActiveColorMode(type, mode);
979}
980
981
982status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
983 android_color_mode_t colorMode) {
984 class MessageSetActiveColorMode: public MessageBase {
985 SurfaceFlinger& mFlinger;
986 sp<IBinder> mDisplay;
987 android_color_mode_t mMode;
988 public:
989 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
990 android_color_mode_t mode) :
991 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
992 virtual bool handler() {
993 Vector<android_color_mode_t> modes;
994 mFlinger.getDisplayColorModes(mDisplay, &modes);
995 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
996 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600997 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
998 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700999 return true;
1000 }
1001 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1002 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001003 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1004 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001005 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001006 ALOGW("Attempt to set active color mode %s %d for virtual display",
1007 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001008 } else {
1009 mFlinger.setActiveColorModeInternal(hw, mMode);
1010 }
1011 return true;
1012 }
1013 };
1014 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1015 postMessageSync(msg);
1016 return NO_ERROR;
1017}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001018
Svetoslavd85084b2014-03-20 10:28:31 -07001019status_t SurfaceFlinger::clearAnimationFrameStats() {
1020 Mutex::Autolock _l(mStateLock);
1021 mAnimFrameTracker.clearStats();
1022 return NO_ERROR;
1023}
1024
1025status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1026 Mutex::Autolock _l(mStateLock);
1027 mAnimFrameTracker.getStats(outStats);
1028 return NO_ERROR;
1029}
1030
Dan Stozac4f471e2016-03-24 09:31:08 -07001031status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1032 HdrCapabilities* outCapabilities) const {
1033 Mutex::Autolock _l(mStateLock);
1034
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001035 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001036 if (displayDevice == nullptr) {
1037 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1038 return BAD_VALUE;
1039 }
1040
1041 std::unique_ptr<HdrCapabilities> capabilities =
1042 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
1043 if (capabilities) {
1044 std::swap(*outCapabilities, *capabilities);
1045 } else {
1046 return BAD_VALUE;
1047 }
1048
1049 return NO_ERROR;
1050}
1051
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001052status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
1053 if (enable == mInjectVSyncs) {
1054 return NO_ERROR;
1055 }
1056
1057 if (enable) {
1058 mInjectVSyncs = enable;
1059 ALOGV("VSync Injections enabled");
1060 if (mVSyncInjector.get() == nullptr) {
1061 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -07001062 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001063 }
1064 mEventQueue.setEventThread(mInjectorEventThread);
1065 } else {
1066 mInjectVSyncs = enable;
1067 ALOGV("VSync Injections disabled");
1068 mEventQueue.setEventThread(mSFEventThread);
1069 mVSyncInjector.clear();
1070 }
1071 return NO_ERROR;
1072}
1073
1074status_t SurfaceFlinger::injectVSync(nsecs_t when) {
1075 if (!mInjectVSyncs) {
1076 ALOGE("VSync Injections not enabled");
1077 return BAD_VALUE;
1078 }
1079 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1080 ALOGV("Injecting VSync inside SurfaceFlinger");
1081 mVSyncInjector->onInjectSyncEvent(when);
1082 }
1083 return NO_ERROR;
1084}
1085
Kalle Raitaa099a242017-01-11 11:17:29 -08001086status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const {
1087 IPCThreadState* ipc = IPCThreadState::self();
1088 const int pid = ipc->getCallingPid();
1089 const int uid = ipc->getCallingUid();
1090 if ((uid != AID_SHELL) &&
1091 !PermissionCache::checkPermission(sDump, pid, uid)) {
1092 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1093 return PERMISSION_DENIED;
1094 }
1095
1096 // Try to acquire a lock for 1s, fail gracefully
1097 const status_t err = mStateLock.timedLock(s2ns(1));
1098 const bool locked = (err == NO_ERROR);
1099 if (!locked) {
1100 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1101 return TIMED_OUT;
1102 }
1103
1104 outLayers->clear();
1105 mCurrentState.traverseInZOrder([&](Layer* layer) {
1106 outLayers->push_back(layer->getLayerDebugInfo());
1107 });
1108
1109 mStateLock.unlock();
1110 return NO_ERROR;
1111}
1112
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001113// ----------------------------------------------------------------------------
1114
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001115sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1116 ISurfaceComposer::VsyncSource vsyncSource) {
1117 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1118 return mSFEventThread->createEventConnection();
1119 } else {
1120 return mEventThread->createEventConnection();
1121 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001122}
1123
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001124// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001125
1126void SurfaceFlinger::waitForEvent() {
1127 mEventQueue.waitMessage();
1128}
1129
1130void SurfaceFlinger::signalTransaction() {
1131 mEventQueue.invalidate();
1132}
1133
1134void SurfaceFlinger::signalLayerUpdate() {
1135 mEventQueue.invalidate();
1136}
1137
1138void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001139 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001140 mEventQueue.refresh();
1141}
1142
1143status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001144 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001145 return mEventQueue.postMessage(msg, reltime);
1146}
1147
1148status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001149 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001150 status_t res = mEventQueue.postMessage(msg, reltime);
1151 if (res == NO_ERROR) {
1152 msg->wait();
1153 }
1154 return res;
1155}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001156
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001157void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001158 do {
1159 waitForEvent();
1160 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001161}
1162
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001163void SurfaceFlinger::enableHardwareVsync() {
1164 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001165 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001166 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001167 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1168 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001169 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001170 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001171}
1172
Jesse Hall948fe0c2013-10-14 12:56:09 -07001173void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001174 Mutex::Autolock _l(mHWVsyncLock);
1175
Jesse Hall948fe0c2013-10-14 12:56:09 -07001176 if (makeAvailable) {
1177 mHWVsyncAvailable = true;
1178 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001179 // Hardware vsync is not currently available, so abort the resync
1180 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001181 return;
1182 }
1183
Dan Stoza9e56aa02015-11-02 13:00:03 -08001184 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1185 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001186
1187 mPrimaryDispSync.reset();
1188 mPrimaryDispSync.setPeriod(period);
1189
1190 if (!mPrimaryHWVsyncEnabled) {
1191 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001192 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1193 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001194 mPrimaryHWVsyncEnabled = true;
1195 }
1196}
1197
Jesse Hall948fe0c2013-10-14 12:56:09 -07001198void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001199 Mutex::Autolock _l(mHWVsyncLock);
1200 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001201 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1202 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001203 mPrimaryDispSync.endResync();
1204 mPrimaryHWVsyncEnabled = false;
1205 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001206 if (makeUnavailable) {
1207 mHWVsyncAvailable = false;
1208 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001209}
1210
Tim Murray4a4e4a22016-04-19 16:29:23 +00001211void SurfaceFlinger::resyncWithRateLimit() {
1212 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001213
1214 // No explicit locking is needed here since EventThread holds a lock while calling this method
1215 static nsecs_t sLastResyncAttempted = 0;
1216 const nsecs_t now = systemTime();
1217 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001218 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001219 }
Dan Stoza57164302017-05-08 14:03:54 -07001220 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001221}
1222
Steven Thomasb02664d2017-07-26 18:48:28 -07001223void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1224 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001225 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001226 // Ignore any vsyncs from a previous hardware composer.
1227 if (sequenceId != mComposerSequenceId) {
1228 return;
1229 }
1230
1231 int32_t type;
1232 if (!mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001233 return;
1234 }
1235
Jamie Gennisd1700752013-10-14 12:22:52 -07001236 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001237
Jamie Gennisd1700752013-10-14 12:22:52 -07001238 { // Scope for the lock
1239 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001240 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001241 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001242 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001243 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001244
1245 if (needsHwVsync) {
1246 enableHardwareVsync();
1247 } else {
1248 disableHardwareVsync(false);
1249 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001250}
1251
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001252void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001253 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001254 *compositorTiming = mCompositorTiming;
1255}
1256
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001257void SurfaceFlinger::createDefaultDisplayDevice() {
Steven Thomasb02664d2017-07-26 18:48:28 -07001258 const DisplayDevice::DisplayType type = DisplayDevice::DISPLAY_PRIMARY;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001259 wp<IBinder> token = mBuiltinDisplays[type];
1260
1261 // All non-virtual displays are currently considered secure.
1262 const bool isSecure = true;
1263
1264 sp<IGraphicBufferProducer> producer;
1265 sp<IGraphicBufferConsumer> consumer;
1266 BufferQueue::createBufferQueue(&producer, &consumer);
1267
1268 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1269
1270 bool hasWideColorModes = false;
1271 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1272 for (android_color_mode_t colorMode : modes) {
1273 switch (colorMode) {
1274 case HAL_COLOR_MODE_DISPLAY_P3:
1275 case HAL_COLOR_MODE_ADOBE_RGB:
1276 case HAL_COLOR_MODE_DCI_P3:
1277 hasWideColorModes = true;
1278 break;
1279 default:
1280 break;
1281 }
1282 }
1283 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
1284 token, fbs, producer, mRenderEngine->getEGLConfig(),
1285 hasWideColorModes && hasWideColorDisplay);
1286 mDisplays.add(token, hw);
Romain Guyc53d3552017-07-20 18:49:46 -07001287 setActiveColorModeInternal(hw, HAL_COLOR_MODE_NATIVE);
Courtney Goeltzenleuchter79d27242017-07-13 17:54:01 -06001288 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Steven Thomasb02664d2017-07-26 18:48:28 -07001289
1290 // Add the primary display token to mDrawingState so we don't try to
1291 // recreate the DisplayDevice for the primary display.
1292 mDrawingState.displays.add(token, DisplayDeviceState(type, true));
1293
1294 // make the GLContext current so that we can create textures when creating
1295 // Layers (which may happens before we render something)
1296 hw->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001297}
1298
Steven Thomasb02664d2017-07-26 18:48:28 -07001299void SurfaceFlinger::onHotplugReceived(int32_t sequenceId,
1300 hwc2_display_t display, HWC2::Connection connection,
1301 bool primaryDisplay) {
1302 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s, %s)",
1303 sequenceId, display,
1304 connection == HWC2::Connection::Connected ?
1305 "connected" : "disconnected",
1306 primaryDisplay ? "primary" : "external");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001307
Steven Thomasb02664d2017-07-26 18:48:28 -07001308 // Only lock if we're not on the main thread. This function is normally
1309 // called on a hwbinder thread, but for the primary display it's called on
1310 // the main thread with the state lock already held, so don't attempt to
1311 // acquire it here.
1312 ConditionalLock lock(mStateLock,
1313 std::this_thread::get_id() != mMainThreadId);
1314
1315 if (primaryDisplay) {
1316 mHwc->onHotplug(display, connection);
1317 if (!mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY].get()) {
1318 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001319 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001320 createDefaultDisplayDevice();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001321 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07001322 if (sequenceId != mComposerSequenceId) {
1323 return;
1324 }
1325 if (mHwc->isUsingVrComposer()) {
1326 ALOGE("External displays are not supported by the vr hardware composer.");
1327 return;
1328 }
1329 mHwc->onHotplug(display, connection);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001330 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Steven Thomasb02664d2017-07-26 18:48:28 -07001331 if (connection == HWC2::Connection::Connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001332 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001333 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001334 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1335 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001336 }
1337 setTransactionFlags(eDisplayTransactionNeeded);
1338
Andy McFadden9e9689c2012-10-10 18:17:51 -07001339 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001340 }
Mathias Agopian86303202012-07-24 22:46:10 -07001341}
1342
Steven Thomasb02664d2017-07-26 18:48:28 -07001343void SurfaceFlinger::onRefreshReceived(int sequenceId,
1344 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001345 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001346 if (sequenceId != mComposerSequenceId) {
1347 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001348 }
Steven Thomasb02664d2017-07-26 18:48:28 -07001349 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001350}
1351
Dan Stoza9e56aa02015-11-02 13:00:03 -08001352void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001353 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001354 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001355 getHwComposer().setVsyncEnabled(disp,
1356 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001357}
1358
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001359// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001360void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001361 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001362 // Clear the drawing state so that the logic inside of
1363 // handleTransactionLocked will fire. It will determine the delta between
1364 // mCurrentState and mDrawingState and re-apply all changes when we make the
1365 // transition.
1366 mDrawingState.displays.clear();
Steven Thomasb02664d2017-07-26 18:48:28 -07001367 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001368 mDisplays.clear();
1369}
1370
Steven Thomas050b2c82017-03-06 11:45:16 -08001371void SurfaceFlinger::updateVrFlinger() {
1372 if (!mVrFlinger)
1373 return;
1374 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1375 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001376 return;
1377 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001378
Steven Thomasb02664d2017-07-26 18:48:28 -07001379 if (vrFlingerRequestsDisplay && !mHwc->getComposer()->isRemote()) {
1380 ALOGE("Vr flinger is only supported for remote hardware composer"
1381 " service connections. Ignoring request to transition to vr"
1382 " flinger.");
1383 mVrFlingerRequestsDisplay = false;
1384 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001385 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001386
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001387 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001388
Steven Thomasb02664d2017-07-26 18:48:28 -07001389 int currentDisplayPowerMode = getDisplayDeviceLocked(
1390 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001391
Steven Thomasb02664d2017-07-26 18:48:28 -07001392 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001393 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001394 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001395
Steven Thomasb02664d2017-07-26 18:48:28 -07001396 resetDisplayState();
1397 mHwc.reset(); // Delete the current instance before creating the new one
1398 mHwc.reset(new HWComposer(
1399 vrFlingerRequestsDisplay ? "vr" : mHwcServiceName));
1400 mHwc->registerCallback(this, ++mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001401
Steven Thomasb02664d2017-07-26 18:48:28 -07001402 LOG_ALWAYS_FATAL_IF(!mHwc->getComposer()->isRemote(),
1403 "Switched to non-remote hardware composer");
1404
1405 if (vrFlingerRequestsDisplay) {
1406 mVrFlinger->GrantDisplayOwnership();
1407 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001408 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001409 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001410
1411 mVisibleRegionsDirty = true;
1412 invalidateHwcGeometry();
1413
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001414 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001415 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1416 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1417 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001418
Steven Thomasb02664d2017-07-26 18:48:28 -07001419 // Reset the timing values to account for the period of the swapped in HWC
1420 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1421 const nsecs_t period = activeConfig->getVsyncPeriod();
1422 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001423
Steven Thomasb02664d2017-07-26 18:48:28 -07001424 // Use phase of 0 since phase is not known.
1425 // Use latency of 0, which will snap to the ideal latency.
1426 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001427
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001428 android_atomic_or(1, &mRepaintEverything);
1429 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001430}
1431
Mathias Agopian4fec8732012-06-29 14:12:52 -07001432void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001433 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001434 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001435 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001436 bool frameMissed = !mHadClientComposition &&
1437 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001438 (mPreviousPresentFence->getSignalTime() ==
1439 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001440 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001441 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001442 signalLayerUpdate();
1443 break;
1444 }
1445
Steven Thomas050b2c82017-03-06 11:45:16 -08001446 // Now that we're going to make it to the handleMessageTransaction()
1447 // call below it's safe to call updateVrFlinger(), which will
1448 // potentially trigger a display handoff.
1449 updateVrFlinger();
1450
Dan Stoza6b9454d2014-11-07 16:00:59 -08001451 bool refreshNeeded = handleMessageTransaction();
1452 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001453 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001454 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001455 // Signal a refresh if a transaction modified the window state,
1456 // a new buffer was latched, or if HWC has requested a full
1457 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001458 signalRefresh();
1459 }
1460 break;
1461 }
1462 case MessageQueue::REFRESH: {
1463 handleMessageRefresh();
1464 break;
1465 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001466 }
1467}
1468
Dan Stoza6b9454d2014-11-07 16:00:59 -08001469bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001470 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001471 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001472 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001473 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001474 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001475 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001476}
1477
Dan Stoza6b9454d2014-11-07 16:00:59 -08001478bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001479 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001480 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001481}
1482
1483void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001484 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001485
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001486 mRefreshPending = false;
1487
Pablo Ceballos40845df2016-01-25 17:41:15 -08001488 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001489
Brian Andersond6927fb2016-07-23 23:37:30 -07001490 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001491 rebuildLayerStacks();
1492 setUpHWComposer();
1493 doDebugFlashRegions();
1494 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001495 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001496
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001497 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001498
1499 mHadClientComposition = false;
1500 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1501 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1502 mHadClientComposition = mHadClientComposition ||
1503 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1504 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001505
Dan Stoza9e56aa02015-11-02 13:00:03 -08001506 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001507}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001508
Mathias Agopiancd60f992012-08-16 16:28:27 -07001509void SurfaceFlinger::doDebugFlashRegions()
1510{
1511 // is debugging enabled
1512 if (CC_LIKELY(!mDebugRegion))
1513 return;
1514
1515 const bool repaintEverything = mRepaintEverything;
1516 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1517 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001518 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001519 // transform the dirty region into this screen's coordinate space
1520 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1521 if (!dirtyRegion.isEmpty()) {
1522 // redraw the whole screen
1523 doComposeSurfaces(hw, Region(hw->bounds()));
1524
1525 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001526 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001527 RenderEngine& engine(getRenderEngine());
1528 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1529
Mathias Agopianda27af92012-09-13 18:17:13 -07001530 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001531 }
1532 }
1533 }
1534
1535 postFramebuffer();
1536
1537 if (mDebugRegion > 1) {
1538 usleep(mDebugRegion * 1000);
1539 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001540
Dan Stoza9e56aa02015-11-02 13:00:03 -08001541 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001542 auto& displayDevice = mDisplays[displayId];
1543 if (!displayDevice->isDisplayOn()) {
1544 continue;
1545 }
1546
1547 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001548 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1549 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001550 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001551}
1552
Brian Andersond6927fb2016-07-23 23:37:30 -07001553void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001554{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001555 ATRACE_CALL();
1556 ALOGV("preComposition");
1557
Mathias Agopiancd60f992012-08-16 16:28:27 -07001558 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001559 mDrawingState.traverseInZOrder([&](Layer* layer) {
1560 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001561 needExtraInvalidate = true;
1562 }
Robert Carr2047fae2016-11-28 14:09:09 -08001563 });
1564
Mathias Agopiancd60f992012-08-16 16:28:27 -07001565 if (needExtraInvalidate) {
1566 signalLayerUpdate();
1567 }
1568}
1569
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001570void SurfaceFlinger::updateCompositorTiming(
1571 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1572 std::shared_ptr<FenceTime>& presentFenceTime) {
1573 // Update queue of past composite+present times and determine the
1574 // most recently known composite to present latency.
1575 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1576 nsecs_t compositeToPresentLatency = -1;
1577 while (!mCompositePresentTimes.empty()) {
1578 CompositePresentTime& cpt = mCompositePresentTimes.front();
1579 // Cached values should have been updated before calling this method,
1580 // which helps avoid duplicate syscalls.
1581 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1582 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1583 break;
1584 }
1585 compositeToPresentLatency = displayTime - cpt.composite;
1586 mCompositePresentTimes.pop();
1587 }
1588
1589 // Don't let mCompositePresentTimes grow unbounded, just in case.
1590 while (mCompositePresentTimes.size() > 16) {
1591 mCompositePresentTimes.pop();
1592 }
1593
Brian Andersond0010582017-03-07 13:20:31 -08001594 setCompositorTimingSnapped(
1595 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1596}
1597
1598void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1599 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001600 // Integer division and modulo round toward 0 not -inf, so we need to
1601 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001602 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001603 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1604 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1605
Brian Andersond0010582017-03-07 13:20:31 -08001606 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1607 if (idealLatency <= 0) {
1608 idealLatency = vsyncInterval;
1609 }
1610
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001611 // Snap the latency to a value that removes scheduling jitter from the
1612 // composition and present times, which often have >1ms of jitter.
1613 // Reducing jitter is important if an app attempts to extrapolate
1614 // something (such as user input) to an accurate diasplay time.
1615 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1616 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001617 nsecs_t bias = vsyncInterval / 2;
1618 int64_t extraVsyncs =
1619 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1620 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1621 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001622
Brian Andersond0010582017-03-07 13:20:31 -08001623 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001624 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1625 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001626 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001627}
1628
1629void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001630{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001631 ATRACE_CALL();
1632 ALOGV("postComposition");
1633
Brian Anderson3546a3f2016-07-14 11:51:14 -07001634 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001635 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001636 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001637 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001638 }
1639
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001640 // |mStateLock| not needed as we are on the main thread
1641 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001642
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001643 mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001644 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1645 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1646 glCompositionDoneFenceTime =
1647 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1648 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1649 } else {
1650 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1651 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001652
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001653 mDisplayTimeline.updateSignalTimes();
Brian Anderson4e606e32017-03-16 15:34:57 -07001654 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1655 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1656 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001657
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001658 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1659 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1660
1661 // We use the refreshStartTime which might be sampled a little later than
1662 // when we started doing work for this frame, but that should be okay
1663 // since updateCompositorTiming has snapping logic.
1664 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001665 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001666 CompositorTiming compositorTiming;
1667 {
1668 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1669 compositorTiming = mCompositorTiming;
1670 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001671
Robert Carr2047fae2016-11-28 14:09:09 -08001672 mDrawingState.traverseInZOrder([&](Layer* layer) {
1673 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001674 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001675 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001676 recordBufferingStats(layer->getName().string(),
1677 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001678 }
Robert Carr2047fae2016-11-28 14:09:09 -08001679 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001680
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001681 if (presentFenceTime->isValid()) {
1682 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001683 enableHardwareVsync();
1684 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001685 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001686 }
1687 }
1688
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001689 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001690 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001691 enableHardwareVsync();
1692 }
1693 }
1694
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001695 if (mAnimCompositionPending) {
1696 mAnimCompositionPending = false;
1697
Brian Anderson4e606e32017-03-16 15:34:57 -07001698 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001699 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001700 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001701 } else {
1702 // The HWC doesn't support present fences, so use the refresh
1703 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001704 nsecs_t presentTime =
1705 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001706 mAnimFrameTracker.setActualPresentTime(presentTime);
1707 }
1708 mAnimFrameTracker.advanceFrame();
1709 }
Dan Stozab90cf072015-03-05 11:05:59 -08001710
1711 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1712 return;
1713 }
1714
1715 nsecs_t currentTime = systemTime();
1716 if (mHasPoweredOff) {
1717 mHasPoweredOff = false;
1718 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001719 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001720 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001721 if (numPeriods < NUM_BUCKETS - 1) {
1722 mFrameBuckets[numPeriods] += elapsedTime;
1723 } else {
1724 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1725 }
1726 mTotalTime += elapsedTime;
1727 }
1728 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001729}
1730
1731void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001732 ATRACE_CALL();
1733 ALOGV("rebuildLayerStacks");
1734
Mathias Agopiancd60f992012-08-16 16:28:27 -07001735 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001736 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1737 ATRACE_CALL();
1738 mVisibleRegionsDirty = false;
1739 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001740
Jeff Sharkey76488112017-02-27 14:15:18 -07001741 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1742 Region opaqueRegion;
1743 Region dirtyRegion;
1744 Vector<sp<Layer>> layersSortedByZ;
1745 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1746 const Transform& tr(displayDevice->getTransform());
1747 const Rect bounds(displayDevice->getBounds());
1748 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001749 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001750
Jeff Sharkey76488112017-02-27 14:15:18 -07001751 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001752 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1753 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001754 Region drawRegion(tr.transform(
1755 layer->visibleNonTransparentRegion));
1756 drawRegion.andSelf(bounds);
1757 if (!drawRegion.isEmpty()) {
1758 layersSortedByZ.add(layer);
1759 } else {
1760 // Clear out the HWC layer if this layer was
1761 // previously visible, but no longer is
Steven Thomasb02664d2017-07-26 18:48:28 -07001762 layer->destroyHwcLayer(
1763 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001764 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001765 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001766 // WM changes displayDevice->layerStack upon sleep/awake.
1767 // Here we make sure we delete the HWC layers even if
1768 // WM changed their layer stack.
Steven Thomasb02664d2017-07-26 18:48:28 -07001769 layer->destroyHwcLayer(displayDevice->getHwcDisplayId());
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001770 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001771 });
1772 }
1773 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1774 displayDevice->undefinedRegion.set(bounds);
1775 displayDevice->undefinedRegion.subtractSelf(
1776 tr.transform(opaqueRegion));
1777 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001778 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001779 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001780}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001781
Romain Guy0147a172017-06-01 13:53:56 -07001782mat4 SurfaceFlinger::computeSaturationMatrix() const {
1783 if (mSaturation == 1.0f) {
1784 return mat4();
1785 }
1786
1787 // Rec.709 luma coefficients
1788 float3 luminance{0.213f, 0.715f, 0.072f};
1789 luminance *= 1.0f - mSaturation;
1790 return mat4(
1791 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1792 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1793 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1794 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1795 );
1796}
1797
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001798// pickColorMode translates a given dataspace into the best available color mode.
1799// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001800android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001801 switch (dataSpace) {
1802 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1803 // system expects.
1804 case HAL_DATASPACE_UNKNOWN:
1805 case HAL_DATASPACE_SRGB:
1806 case HAL_DATASPACE_V0_SRGB:
1807 return HAL_COLOR_MODE_SRGB;
1808 break;
1809
1810 case HAL_DATASPACE_DISPLAY_P3:
1811 return HAL_COLOR_MODE_DISPLAY_P3;
1812 break;
1813
1814 default:
1815 // TODO (courtneygo): Do we want to assert an error here?
1816 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1817 dataSpace);
1818 return HAL_COLOR_MODE_SRGB;
1819 break;
1820 }
1821}
1822
Romain Guy0147a172017-06-01 13:53:56 -07001823android_dataspace SurfaceFlinger::bestTargetDataSpace(
1824 android_dataspace a, android_dataspace b) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001825 // Only support sRGB and Display-P3 right now.
1826 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1827 return HAL_DATASPACE_DISPLAY_P3;
1828 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001829 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1830 return HAL_DATASPACE_DISPLAY_P3;
1831 }
1832 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1833 return HAL_DATASPACE_DISPLAY_P3;
1834 }
1835
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001836 return HAL_DATASPACE_V0_SRGB;
1837}
1838
Mathias Agopiancd60f992012-08-16 16:28:27 -07001839void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001840 ATRACE_CALL();
1841 ALOGV("setUpHWComposer");
1842
Jesse Hall028dc8f2013-08-20 16:35:32 -07001843 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001844 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1845 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1846 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1847
1848 // If nothing has changed (!dirty), don't recompose.
1849 // If something changed, but we don't currently have any visible layers,
1850 // and didn't when we last did a composition, then skip it this time.
1851 // The second rule does two things:
1852 // - When all layers are removed from a display, we'll emit one black
1853 // frame, then nothing more until we get new layers.
1854 // - When a display is created with a private layer stack, we won't
1855 // emit any black frames until a layer is added to the layer stack.
1856 bool mustRecompose = dirty && !(empty && wasEmpty);
1857
1858 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1859 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1860 mustRecompose ? "doing" : "skipping",
1861 dirty ? "+" : "-",
1862 empty ? "+" : "-",
1863 wasEmpty ? "+" : "-");
1864
Dan Stoza71433162014-02-04 16:22:36 -08001865 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001866
1867 if (mustRecompose) {
1868 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1869 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001870 }
1871
Dan Stoza9e56aa02015-11-02 13:00:03 -08001872 // build the h/w work list
1873 if (CC_UNLIKELY(mGeometryInvalid)) {
1874 mGeometryInvalid = false;
1875 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1876 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1877 const auto hwcId = displayDevice->getHwcDisplayId();
1878 if (hwcId >= 0) {
1879 const Vector<sp<Layer>>& currentLayers(
1880 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001881 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001882 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001883 if (!layer->hasHwcLayer(hwcId)) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001884 if (!layer->createHwcLayer(mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001885 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001886 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001887 }
1888 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001889
Robert Carrae060832016-11-28 10:51:00 -08001890 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001891 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001892 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001893 }
1894 }
1895 }
1896 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001897 }
Riley Andrews03414a12014-07-01 14:22:59 -07001898
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001899
Romain Guy0147a172017-06-01 13:53:56 -07001900 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001901
Dan Stoza9e56aa02015-11-02 13:00:03 -08001902 // Set the per-frame data
1903 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1904 auto& displayDevice = mDisplays[displayId];
1905 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001906
Dan Stoza9e56aa02015-11-02 13:00:03 -08001907 if (hwcId < 0) {
1908 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001909 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001910 if (colorMatrix != mPreviousColorMatrix) {
1911 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1912 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1913 "display %zd: %d", displayId, result);
1914 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001915 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1916 layer->setPerFrameData(displayDevice);
1917 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001918
1919 if (hasWideColorDisplay) {
1920 android_color_mode newColorMode;
1921 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1922
1923 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1924 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1925 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1926 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1927 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1928 }
1929 newColorMode = pickColorMode(newDataSpace);
1930
Romain Guyc53d3552017-07-20 18:49:46 -07001931 // We want the color mode of the boot animation to match that of the bootloader
1932 // To achieve this we suppress color mode changes until after the boot animation
1933 if (mBootFinished) {
1934 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter79d27242017-07-13 17:54:01 -06001935 displayDevice->setCompositionDataSpace(newDataSpace);
Romain Guyc53d3552017-07-20 18:49:46 -07001936 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001937 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001938 }
1939
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001940 mPreviousColorMatrix = colorMatrix;
1941
Dan Stoza9e56aa02015-11-02 13:00:03 -08001942 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001943 auto& displayDevice = mDisplays[displayId];
1944 if (!displayDevice->isDisplayOn()) {
1945 continue;
1946 }
1947
1948 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001949 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1950 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001951 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001952}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001953
Mathias Agopiancd60f992012-08-16 16:28:27 -07001954void SurfaceFlinger::doComposition() {
1955 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001956 ALOGV("doComposition");
1957
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001958 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001959 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001960 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001961 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001962 // transform the dirty region into this screen's coordinate space
1963 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001964
1965 // repaint the framebuffer (if needed)
1966 doDisplayComposition(hw, dirtyRegion);
1967
Mathias Agopiancd60f992012-08-16 16:28:27 -07001968 hw->dirtyRegion.clear();
1969 hw->flip(hw->swapRegion);
1970 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001971 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001972 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001973 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001974}
1975
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001976void SurfaceFlinger::postFramebuffer()
1977{
Mathias Agopian841cde52012-03-01 15:44:37 -08001978 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001979 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001980
Mathias Agopiana44b0412011-10-16 18:46:35 -07001981 const nsecs_t now = systemTime();
1982 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001983
Dan Stoza9e56aa02015-11-02 13:00:03 -08001984 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1985 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001986 if (!displayDevice->isDisplayOn()) {
1987 continue;
1988 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001989 const auto hwcId = displayDevice->getHwcDisplayId();
1990 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001991 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001992 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001993 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001994 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001995 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1996 sp<Fence> releaseFence = Fence::NO_FENCE;
1997 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1998 releaseFence = displayDevice->getClientTargetAcquireFence();
1999 } else {
2000 auto hwcLayer = layer->getHwcLayer(hwcId);
2001 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002002 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002003 layer->onLayerDisplayed(releaseFence);
2004 }
2005 if (hwcId >= 0) {
2006 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002007 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002008 }
2009
Mathias Agopiana44b0412011-10-16 18:46:35 -07002010 mLastSwapBufferTime = systemTime() - now;
2011 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002012
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002013 // |mStateLock| not needed as we are on the main thread
2014 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002015 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2016 logFrameStats();
2017 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002018}
2019
Mathias Agopian87baae12012-07-31 12:38:26 -07002020void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002021{
Mathias Agopian841cde52012-03-01 15:44:37 -08002022 ATRACE_CALL();
2023
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002024 // here we keep a copy of the drawing state (that is the state that's
2025 // going to be overwritten by handleTransactionLocked()) outside of
2026 // mStateLock so that the side-effects of the State assignment
2027 // don't happen with mStateLock held (which can cause deadlocks).
2028 State drawingState(mDrawingState);
2029
Mathias Agopianca4d3602011-05-19 15:38:14 -07002030 Mutex::Autolock _l(mStateLock);
2031 const nsecs_t now = systemTime();
2032 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002033
Mathias Agopianca4d3602011-05-19 15:38:14 -07002034 // Here we're guaranteed that some transaction flags are set
2035 // so we can call handleTransactionLocked() unconditionally.
2036 // We call getTransactionFlags(), which will also clear the flags,
2037 // with mStateLock held to guarantee that mCurrentState won't change
2038 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002039
Mathias Agopiane57f2922012-08-09 16:29:12 -07002040 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002041 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002042
Mathias Agopianca4d3602011-05-19 15:38:14 -07002043 mLastTransactionTime = systemTime() - now;
2044 mDebugInTransaction = 0;
2045 invalidateHwcGeometry();
2046 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002047}
2048
Mathias Agopian87baae12012-07-31 12:38:26 -07002049void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002050{
Dan Stoza7dde5992015-05-22 09:51:44 -07002051 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002052 mCurrentState.traverseInZOrder([](Layer* layer) {
2053 layer->notifyAvailableFrames();
2054 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002055
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002056 /*
2057 * Traversal of the children
2058 * (perform the transaction for each of them if needed)
2059 */
2060
Mathias Agopian3559b072012-08-15 13:46:03 -07002061 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002062 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002063 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002064 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002065
2066 const uint32_t flags = layer->doTransaction(0);
2067 if (flags & Layer::eVisibleRegion)
2068 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002069 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002070 }
2071
2072 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002073 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002074 */
2075
Mathias Agopiane57f2922012-08-09 16:29:12 -07002076 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002077 // here we take advantage of Vector's copy-on-write semantics to
2078 // improve performance by skipping the transaction entirely when
2079 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07002080 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2081 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002082 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002083 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07002084 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07002085 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07002086
2087 // find the displays that were removed
2088 // (ie: in drawing state but not in current state)
2089 // also handle displays that changed
2090 // (ie: displays that are in both lists)
2091 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002092 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2093 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002094 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002095 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07002096 // Call makeCurrent() on the primary display so we can
2097 // be sure that nothing associated with this display
2098 // is current.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002099 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
Mathias Agopian875d8e12013-06-07 15:35:48 -07002100 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002101 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
Jesse Hall02d86562013-03-25 14:43:23 -07002102 if (hw != NULL)
2103 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07002104 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08002105 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07002106 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07002107 } else {
2108 ALOGW("trying to remove the main display");
2109 }
2110 } else {
2111 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07002112 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002113 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08002114 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2115 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07002116 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002117 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07002118 // recreating the DisplayDevice, so we just remove it
2119 // from the drawing state, so that it get re-added
2120 // below.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002121 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
Jesse Hall02d86562013-03-25 14:43:23 -07002122 if (hw != NULL)
2123 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07002124 mDisplays.removeItem(display);
2125 mDrawingState.displays.removeItemsAt(i);
2126 dc--; i--;
2127 // at this point we must loop to the next item
2128 continue;
2129 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002130
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002131 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07002132 if (disp != NULL) {
2133 if (state.layerStack != draw[i].layerStack) {
2134 disp->setLayerStack(state.layerStack);
2135 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002136 if ((state.orientation != draw[i].orientation)
2137 || (state.viewport != draw[i].viewport)
2138 || (state.frame != draw[i].frame))
2139 {
2140 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002141 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07002142 }
Michael Lentine47e45402014-07-18 15:34:25 -07002143 if (state.width != draw[i].width || state.height != draw[i].height) {
2144 disp->setDisplaySize(state.width, state.height);
2145 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002146 }
2147 }
2148 }
2149
2150 // find displays that were added
2151 // (ie: in current state but not in drawing state)
2152 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002153 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002154 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002155
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002156 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002157 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002158 sp<IGraphicBufferProducer> bqProducer;
2159 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian0556d792017-03-22 15:49:32 -07002160 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002161
Dan Stoza9e56aa02015-11-02 13:00:03 -08002162 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002163 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002164 // Virtual displays without a surface are dormant:
2165 // they have external state (layer stack, projection,
2166 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002167 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002168
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002169 // Allow VR composer to use virtual displays.
Steven Thomasb02664d2017-07-26 18:48:28 -07002170 if (mUseHwcVirtualDisplays || mHwc->isUsingVrComposer()) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002171 int width = 0;
2172 int status = state.surface->query(
2173 NATIVE_WINDOW_WIDTH, &width);
2174 ALOGE_IF(status != NO_ERROR,
2175 "Unable to query width (%d)", status);
2176 int height = 0;
2177 status = state.surface->query(
2178 NATIVE_WINDOW_HEIGHT, &height);
2179 ALOGE_IF(status != NO_ERROR,
2180 "Unable to query height (%d)", status);
2181 int intFormat = 0;
2182 status = state.surface->query(
2183 NATIVE_WINDOW_FORMAT, &intFormat);
2184 ALOGE_IF(status != NO_ERROR,
2185 "Unable to query format (%d)", status);
2186 auto format = static_cast<android_pixel_format_t>(
2187 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002188
Dan Stoza8cf150a2016-08-02 10:27:31 -07002189 mHwc->allocateVirtualDisplay(width, height, &format,
2190 &hwcId);
2191 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002192
Dan Stoza5cf424b2016-05-20 14:02:39 -07002193 // TODO: Plumb requested format back up to consumer
2194
Dan Stoza9e56aa02015-11-02 13:00:03 -08002195 sp<VirtualDisplaySurface> vds =
2196 new VirtualDisplaySurface(*mHwc,
2197 hwcId, state.surface, bqProducer,
2198 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002199
2200 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002201 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002202 }
2203 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002204 ALOGE_IF(state.surface!=NULL,
2205 "adding a supported display, but rendering "
2206 "surface is provided (%p), ignoring it",
2207 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002208
2209 hwcId = state.type;
2210 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2211 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002212 }
2213
2214 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002215 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002216 sp<DisplayDevice> hw =
2217 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2218 dispSurface, producer,
2219 mRenderEngine->getEGLConfig(),
2220 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002221 hw->setLayerStack(state.layerStack);
2222 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002223 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002224 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002225 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002226 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002227 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002228 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002229 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002230 }
2231 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002232 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002233 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002234
Mathias Agopian84300952012-11-21 16:02:13 -08002235 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2236 // The transform hint might have changed for some layers
2237 // (either because a display has changed, or because a layer
2238 // as changed).
2239 //
2240 // Walk through all the layers in currentLayers,
2241 // and update their transform hint.
2242 //
2243 // If a layer is visible only on a single display, then that
2244 // display is used to calculate the hint, otherwise we use the
2245 // default display.
2246 //
2247 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2248 // the hint is set before we acquire a buffer from the surface texture.
2249 //
2250 // NOTE: layer transactions have taken place already, so we use their
2251 // drawing state. However, SurfaceFlinger's own transaction has not
2252 // happened yet, so we must use the current state layer list
2253 // (soon to become the drawing state list).
2254 //
2255 sp<const DisplayDevice> disp;
2256 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002257 bool first = true;
2258 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002259 // NOTE: we rely on the fact that layers are sorted by
2260 // layerStack first (so we don't have to traverse the list
2261 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002262 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002263 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002264 currentlayerStack = layerStack;
2265 // figure out if this layerstack is mirrored
2266 // (more than one display) if so, pick the default display,
2267 // if not, pick the only display it's on.
2268 disp.clear();
2269 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2270 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002271 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian84300952012-11-21 16:02:13 -08002272 if (disp == NULL) {
2273 disp = hw;
2274 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002275 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002276 break;
2277 }
2278 }
2279 }
2280 }
Chet Haase91d25932013-04-11 15:24:55 -07002281 if (disp == NULL) {
2282 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2283 // redraw after transform hint changes. See bug 8508397.
2284
2285 // could be null when this layer is using a layerStack
2286 // that is not visible on any display. Also can occur at
2287 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002288 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002289 }
Chet Haase91d25932013-04-11 15:24:55 -07002290 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002291
2292 first = false;
2293 });
Mathias Agopian84300952012-11-21 16:02:13 -08002294 }
2295
2296
Mathias Agopian3559b072012-08-15 13:46:03 -07002297 /*
2298 * Perform our own transaction if needed
2299 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002300
2301 if (mLayersAdded) {
2302 mLayersAdded = false;
2303 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002304 mVisibleRegionsDirty = true;
2305 }
2306
2307 // some layers might have been removed, so
2308 // we need to update the regions they're exposing.
2309 if (mLayersRemoved) {
2310 mLayersRemoved = false;
2311 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002312 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002313 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002314 // this layer is not visible anymore
2315 // TODO: we could traverse the tree from front to back and
2316 // compute the actual visible region
2317 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002318 Region visibleReg;
2319 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002320 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002321 }
Robert Carr2047fae2016-11-28 14:09:09 -08002322 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002323 }
2324
2325 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002326
2327 updateCursorAsync();
2328}
2329
2330void SurfaceFlinger::updateCursorAsync()
2331{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002332 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2333 auto& displayDevice = mDisplays[displayId];
2334 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002335 continue;
2336 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002337
2338 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2339 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002340 }
2341 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002342}
2343
2344void SurfaceFlinger::commitTransaction()
2345{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002346 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002347 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002348 for (const auto& l : mLayersPendingRemoval) {
2349 recordBufferingStats(l->getName().string(),
2350 l->getOccupancyHistory(true));
2351 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002352 }
2353 mLayersPendingRemoval.clear();
2354 }
2355
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002356 // If this transaction is part of a window animation then the next frame
2357 // we composite should be considered an animation as well.
2358 mAnimCompositionPending = mAnimTransactionPending;
2359
Mathias Agopian4fec8732012-06-29 14:12:52 -07002360 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002361 mDrawingState.traverseInZOrder([](Layer* layer) {
2362 layer->commitChildList();
2363 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002364 mTransactionPending = false;
2365 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002366 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002367}
2368
Chia-I Wuab0c3192017-08-01 11:29:00 -07002369void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002370 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002371{
Mathias Agopian841cde52012-03-01 15:44:37 -08002372 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002373 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002374
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002375 Region aboveOpaqueLayers;
2376 Region aboveCoveredLayers;
2377 Region dirty;
2378
Mathias Agopian87baae12012-07-31 12:38:26 -07002379 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002380
Robert Carr2047fae2016-11-28 14:09:09 -08002381 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002382 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002383 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002384
Jesse Hall01e29052013-02-19 16:13:35 -08002385 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002386 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002387 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002388
Mathias Agopianab028732010-03-16 16:41:46 -07002389 /*
2390 * opaqueRegion: area of a surface that is fully opaque.
2391 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002392 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002393
2394 /*
2395 * visibleRegion: area of a surface that is visible on screen
2396 * and not fully transparent. This is essentially the layer's
2397 * footprint minus the opaque regions above it.
2398 * Areas covered by a translucent surface are considered visible.
2399 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002400 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002401
2402 /*
2403 * coveredRegion: area of a surface that is covered by all
2404 * visible regions above it (which includes the translucent areas).
2405 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002406 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002407
Jesse Halla8026d22012-09-25 13:25:04 -07002408 /*
2409 * transparentRegion: area of a surface that is hinted to be completely
2410 * transparent. This is only used to tell when the layer has no visible
2411 * non-transparent regions and can be removed from the layer list. It
2412 * does not affect the visibleRegion of this layer or any layers
2413 * beneath it. The hint may not be correct if apps don't respect the
2414 * SurfaceView restrictions (which, sadly, some don't).
2415 */
2416 Region transparentRegion;
2417
Mathias Agopianab028732010-03-16 16:41:46 -07002418
2419 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002420 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002421 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002422 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002423 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002424 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002425 if (!visibleRegion.isEmpty()) {
2426 // Remove the transparent area from the visible region
2427 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002428 if (tr.preserveRects()) {
2429 // transform the transparent region
2430 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002431 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002432 // transformation too complex, can't do the
2433 // transparent region optimization.
2434 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002435 }
Mathias Agopianab028732010-03-16 16:41:46 -07002436 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002437
Mathias Agopianab028732010-03-16 16:41:46 -07002438 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002439 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002440 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002441 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2442 // the opaque region is the layer's footprint
2443 opaqueRegion = visibleRegion;
2444 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002445 }
2446 }
2447
Mathias Agopianab028732010-03-16 16:41:46 -07002448 // Clip the covered region to the visible region
2449 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2450
2451 // Update aboveCoveredLayers for next (lower) layer
2452 aboveCoveredLayers.orSelf(visibleRegion);
2453
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002454 // subtract the opaque region covered by the layers above us
2455 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002456
2457 // compute this layer's dirty region
2458 if (layer->contentDirty) {
2459 // we need to invalidate the whole region
2460 dirty = visibleRegion;
2461 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002462 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002463 layer->contentDirty = false;
2464 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002465 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002466 * the exposed region consists of two components:
2467 * 1) what's VISIBLE now and was COVERED before
2468 * 2) what's EXPOSED now less what was EXPOSED before
2469 *
2470 * note that (1) is conservative, we start with the whole
2471 * visible region but only keep what used to be covered by
2472 * something -- which mean it may have been exposed.
2473 *
2474 * (2) handles areas that were not covered by anything but got
2475 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002476 */
Mathias Agopianab028732010-03-16 16:41:46 -07002477 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002478 const Region oldVisibleRegion = layer->visibleRegion;
2479 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002480 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2481 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002482 }
2483 dirty.subtractSelf(aboveOpaqueLayers);
2484
2485 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002486 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002487
Mathias Agopianab028732010-03-16 16:41:46 -07002488 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002489 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002490
Jesse Halla8026d22012-09-25 13:25:04 -07002491 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002492 layer->setVisibleRegion(visibleRegion);
2493 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002494 layer->setVisibleNonTransparentRegion(
2495 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002496 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002497
Mathias Agopian87baae12012-07-31 12:38:26 -07002498 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002499}
2500
Chia-I Wuab0c3192017-08-01 11:29:00 -07002501void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002502 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002503 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002504 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002505 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002506 }
2507 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002508}
2509
Dan Stoza6b9454d2014-11-07 16:00:59 -08002510bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002511{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002512 ALOGV("handlePageFlip");
2513
Brian Andersond6927fb2016-07-23 23:37:30 -07002514 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002515
Mathias Agopian4fec8732012-06-29 14:12:52 -07002516 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002517 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002518 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002519
2520 // Store the set of layers that need updates. This set must not change as
2521 // buffers are being latched, as this could result in a deadlock.
2522 // Example: Two producers share the same command stream and:
2523 // 1.) Layer 0 is latched
2524 // 2.) Layer 0 gets a new frame
2525 // 2.) Layer 1 gets a new frame
2526 // 3.) Layer 1 is latched.
2527 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2528 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002529 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002530 if (layer->hasQueuedFrame()) {
2531 frameQueued = true;
2532 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002533 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002534 } else {
2535 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002536 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002537 } else {
2538 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002539 }
Robert Carr2047fae2016-11-28 14:09:09 -08002540 });
2541
Dan Stoza9e56aa02015-11-02 13:00:03 -08002542 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002543 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002544 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002545 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002546 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002547 newDataLatched = true;
2548 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002549 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002550
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002551 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002552
2553 // If we will need to wake up at some time in the future to deal with a
2554 // queued frame that shouldn't be displayed during this vsync period, wake
2555 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002556 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002557 signalLayerUpdate();
2558 }
2559
2560 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002561 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002562}
2563
Mathias Agopianad456f92011-01-13 17:53:01 -08002564void SurfaceFlinger::invalidateHwcGeometry()
2565{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002566 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002567}
2568
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002569
Fabien Sanglard830b8472016-11-30 16:35:58 -08002570void SurfaceFlinger::doDisplayComposition(
2571 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002572 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002573{
Dan Stoza71433162014-02-04 16:22:36 -08002574 // We only need to actually compose the display if:
2575 // 1) It is being handled by hardware composer, which may need this to
2576 // keep its virtual display state machine in sync, or
2577 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002578 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002579 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002580 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002581 return;
2582 }
2583
Dan Stoza9e56aa02015-11-02 13:00:03 -08002584 ALOGV("doDisplayComposition");
2585
Mathias Agopian87baae12012-07-31 12:38:26 -07002586 Region dirtyRegion(inDirtyRegion);
2587
Mathias Agopianb8a55602009-06-26 19:06:36 -07002588 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002589 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002590
Fabien Sanglard830b8472016-11-30 16:35:58 -08002591 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002592 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002593 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2594 // takes a rectangle, we must make sure to update that whole
2595 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002596 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002597 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002598 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002599 // We need to redraw the rectangle that will be updated
2600 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002601 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002602 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002603 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002604 } else {
2605 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002606 dirtyRegion.set(displayDevice->bounds());
2607 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002608 }
2609 }
2610
Fabien Sanglard830b8472016-11-30 16:35:58 -08002611 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002612
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002613 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002614 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002615
2616 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002617 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002618}
2619
Dan Stoza9e56aa02015-11-02 13:00:03 -08002620bool SurfaceFlinger::doComposeSurfaces(
2621 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002622{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002623 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002624
Dan Stoza9e56aa02015-11-02 13:00:03 -08002625 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002626
2627 mat4 oldColorMatrix;
2628 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2629 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2630 if (applyColorMatrix) {
2631 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2632 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2633 }
2634
Dan Stoza9e56aa02015-11-02 13:00:03 -08002635 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2636 if (hasClientComposition) {
2637 ALOGV("hasClientComposition");
2638
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002639#ifdef USE_HWC2
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002640 mRenderEngine->setWideColor(displayDevice->getWideColorSupport());
Romain Guy88d37dd2017-05-26 17:57:05 -07002641 mRenderEngine->setColorMode(displayDevice->getActiveColorMode());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002642#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002643 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002644 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002645 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002646 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002647
2648 // |mStateLock| not needed as we are on the main thread
2649 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002650 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2651 }
2652 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002653 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002654
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002655 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002656 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2657 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002658 // when using overlays, we assume a fully transparent framebuffer
2659 // NOTE: we could reduce how much we need to clear, for instance
2660 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002661 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002662 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002663 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002664 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002665 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002666 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002667
2668 // we remove the scissor part
2669 // we're left with the letterbox region
2670 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002671 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002672
2673 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002674 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002675
2676 // but limit it to the dirty region
2677 region.andSelf(dirty);
2678
Mathias Agopianb9494d52012-04-18 02:28:45 -07002679 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002680 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002681 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002682 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002683 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002684 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002685
Dan Stoza9e56aa02015-11-02 13:00:03 -08002686 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002687 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002688 // scissor on the main display. It should never be needed
2689 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002690 const Rect& bounds(displayDevice->getBounds());
2691 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002692 if (scissor != bounds) {
2693 // scissor doesn't match the screen's dimensions, so we
2694 // need to clear everything outside of it and enable
2695 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002696
Mathias Agopianf45c5102012-10-24 16:29:17 -07002697 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002698 const uint32_t height = displayDevice->getHeight();
2699 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002700 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002701 }
2702 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002703 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002704
Mathias Agopian85d751c2012-08-29 16:59:24 -07002705 /*
2706 * and then, render the layers targeted at the framebuffer
2707 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002708
Dan Stoza9e56aa02015-11-02 13:00:03 -08002709 ALOGV("Rendering client layers");
2710 const Transform& displayTransform = displayDevice->getTransform();
2711 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002712 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002713 bool firstLayer = true;
2714 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2715 const Region clip(dirty.intersect(
2716 displayTransform.transform(layer->visibleRegion)));
2717 ALOGV("Layer: %s", layer->getName().string());
2718 ALOGV(" Composition type: %s",
2719 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002720 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002721 switch (layer->getCompositionType(hwcId)) {
2722 case HWC2::Composition::Cursor:
2723 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002724 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002725 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002726 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002727 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2728 layer->isOpaque(state) && (state.alpha == 1.0f)
2729 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002730 // never clear the very first layer since we're
2731 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002732 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002733 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002734 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002735 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002736 case HWC2::Composition::Client: {
2737 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002738 break;
2739 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002740 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002741 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002742 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002743 } else {
2744 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002745 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002746 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002747 }
2748 } else {
2749 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002750 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002751 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002752 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002753 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002754 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002755 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002756 }
2757 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002758
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002759 if (applyColorMatrix) {
2760 getRenderEngine().setupColorTransform(oldColorMatrix);
2761 }
2762
Mathias Agopianf45c5102012-10-24 16:29:17 -07002763 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002764 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002765 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002766}
2767
Fabien Sanglard830b8472016-11-30 16:35:58 -08002768void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2769 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002770 RenderEngine& engine(getRenderEngine());
2771 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002772}
2773
Dan Stoza7d89d062015-04-30 13:29:25 -07002774status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002775 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002776 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002777 const sp<Layer>& lbc,
2778 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002779{
Dan Stoza7d89d062015-04-30 13:29:25 -07002780 // add this layer to the current state list
2781 {
2782 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002783 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002784 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2785 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002786 return NO_MEMORY;
2787 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002788 if (parent == nullptr) {
2789 mCurrentState.layersSortedByZ.add(lbc);
2790 } else {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002791 if (mCurrentState.layersSortedByZ.indexOf(parent) < 0) {
2792 ALOGE("addClientLayer called with a removed parent");
2793 return NAME_NOT_FOUND;
2794 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002795 parent->addChild(lbc);
2796 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002797
Dan Stoza7d89d062015-04-30 13:29:25 -07002798 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002799 mLayersAdded = true;
2800 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002801 }
2802
Mathias Agopian96f08192010-06-02 23:28:45 -07002803 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002804 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002805
Dan Stoza7d89d062015-04-30 13:29:25 -07002806 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002807}
2808
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002809status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002810 Mutex::Autolock _l(mStateLock);
2811
Robert Carr1f0a16a2016-10-24 16:27:39 -07002812 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002813 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002814 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002815 if (topLevelOnly) {
2816 return NO_ERROR;
2817 }
2818
Chia-I Wu98f1c102017-05-30 14:54:08 -07002819 sp<Layer> ancestor = p;
2820 while (ancestor->getParent() != nullptr) {
2821 ancestor = ancestor->getParent();
2822 }
2823 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2824 ALOGE("removeLayer called with a layer whose parent has been removed");
2825 return NAME_NOT_FOUND;
2826 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002827
2828 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002829 } else {
2830 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002831 }
2832
Robert Carr136e2f62017-02-08 17:54:29 -08002833 // As a matter of normal operation, the LayerCleaner will produce a second
2834 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2835 // so we will succeed in promoting it, but it's already been removed
2836 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2837 // otherwise something has gone wrong and we are leaking the layer.
2838 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002839 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2840 layer->getName().string(),
2841 (p != nullptr) ? p->getName().string() : "no-parent");
2842 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002843 } else if (index < 0) {
2844 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002845 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002846
2847 mLayersPendingRemoval.add(layer);
2848 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002849 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002850 setTransactionFlags(eTransactionNeeded);
2851 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002852}
2853
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002854uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002855 return android_atomic_release_load(&mTransactionFlags);
2856}
2857
Mathias Agopian3f844832013-08-07 21:24:32 -07002858uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002859 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2860}
2861
Mathias Agopian3f844832013-08-07 21:24:32 -07002862uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002863 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2864 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002865 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002866 }
2867 return old;
2868}
2869
Mathias Agopian8b33f032012-07-24 20:43:54 -07002870void SurfaceFlinger::setTransactionState(
2871 const Vector<ComposerState>& state,
2872 const Vector<DisplayState>& displays,
2873 uint32_t flags)
2874{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002875 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002876 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002877 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002878
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002879 if (flags & eAnimation) {
2880 // For window updates that are part of an animation we must wait for
2881 // previous animation "frames" to be handled.
2882 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002883 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002884 if (CC_UNLIKELY(err != NO_ERROR)) {
2885 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002886 // caller after a few seconds.
2887 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2888 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002889 mAnimTransactionPending = false;
2890 break;
2891 }
2892 }
2893 }
2894
Mathias Agopiane57f2922012-08-09 16:29:12 -07002895 size_t count = displays.size();
2896 for (size_t i=0 ; i<count ; i++) {
2897 const DisplayState& s(displays[i]);
2898 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002899 }
2900
Mathias Agopiane57f2922012-08-09 16:29:12 -07002901 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002902 for (size_t i=0 ; i<count ; i++) {
2903 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002904 // Here we need to check that the interface we're given is indeed
2905 // one of our own. A malicious client could give us a NULL
2906 // IInterface, or one of its own or even one of our own but a
2907 // different type. All these situations would cause us to crash.
2908 //
2909 // NOTE: it would be better to use RTTI as we could directly check
2910 // that we have a Client*. however, RTTI is disabled in Android.
2911 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002912 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002913 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002914 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002915 sp<Client> client( static_cast<Client *>(s.client.get()) );
2916 transactionFlags |= setClientStateLocked(client, s.state);
2917 }
2918 }
2919 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002920 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002921
Robert Carr2a7dbb42016-05-24 11:41:28 -07002922 // If a synchronous transaction is explicitly requested without any changes,
2923 // force a transaction anyway. This can be used as a flush mechanism for
2924 // previous async transactions.
2925 if (transactionFlags == 0 && (flags & eSynchronous)) {
2926 transactionFlags = eTransactionNeeded;
2927 }
2928
Mathias Agopian386aa982011-11-07 21:58:03 -08002929 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002930 if (mInterceptor.isEnabled()) {
2931 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2932 }
Irvel468051e2016-06-13 16:44:44 -07002933
Mathias Agopian386aa982011-11-07 21:58:03 -08002934 // this triggers the transaction
2935 setTransactionFlags(transactionFlags);
2936
2937 // if this is a synchronous transaction, wait for it to take effect
2938 // before returning.
2939 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002940 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002941 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002942 if (flags & eAnimation) {
2943 mAnimTransactionPending = true;
2944 }
2945 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002946 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2947 if (CC_UNLIKELY(err != NO_ERROR)) {
2948 // just in case something goes wrong in SF, return to the
2949 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002950 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2951 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002952 break;
2953 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002954 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002955 }
2956}
2957
Mathias Agopiane57f2922012-08-09 16:29:12 -07002958uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2959{
Jesse Hall9a143922012-10-04 16:29:19 -07002960 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2961 if (dpyIdx < 0)
2962 return 0;
2963
Mathias Agopiane57f2922012-08-09 16:29:12 -07002964 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002965 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002966 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002967 const uint32_t what = s.what;
2968 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002969 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002970 disp.surface = s.surface;
2971 flags |= eDisplayTransactionNeeded;
2972 }
2973 }
2974 if (what & DisplayState::eLayerStackChanged) {
2975 if (disp.layerStack != s.layerStack) {
2976 disp.layerStack = s.layerStack;
2977 flags |= eDisplayTransactionNeeded;
2978 }
2979 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002980 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002981 if (disp.orientation != s.orientation) {
2982 disp.orientation = s.orientation;
2983 flags |= eDisplayTransactionNeeded;
2984 }
2985 if (disp.frame != s.frame) {
2986 disp.frame = s.frame;
2987 flags |= eDisplayTransactionNeeded;
2988 }
2989 if (disp.viewport != s.viewport) {
2990 disp.viewport = s.viewport;
2991 flags |= eDisplayTransactionNeeded;
2992 }
2993 }
Michael Lentine47e45402014-07-18 15:34:25 -07002994 if (what & DisplayState::eDisplaySizeChanged) {
2995 if (disp.width != s.width) {
2996 disp.width = s.width;
2997 flags |= eDisplayTransactionNeeded;
2998 }
2999 if (disp.height != s.height) {
3000 disp.height = s.height;
3001 flags |= eDisplayTransactionNeeded;
3002 }
3003 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003004 }
3005 return flags;
3006}
3007
3008uint32_t SurfaceFlinger::setClientStateLocked(
3009 const sp<Client>& client,
3010 const layer_state_t& s)
3011{
3012 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08003013 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07003014 if (layer != 0) {
3015 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07003016 bool geometryAppliesWithResize =
3017 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003018 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07003019 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003020 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07003021 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003022 }
3023 if (what & layer_state_t::eLayerChanged) {
3024 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07003025 const auto& p = layer->getParent();
3026 if (p == nullptr) {
3027 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3028 if (layer->setLayer(s.z) && idx >= 0) {
3029 mCurrentState.layersSortedByZ.removeAt(idx);
3030 mCurrentState.layersSortedByZ.add(layer);
3031 // we need traversal (state changed)
3032 // AND transaction (list changed)
3033 flags |= eTransactionNeeded|eTraversalNeeded;
3034 }
3035 } else {
3036 if (p->setChildLayer(layer, s.z)) {
3037 flags |= eTransactionNeeded|eTraversalNeeded;
3038 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003039 }
3040 }
Robert Carrdb66e622017-04-10 16:55:57 -07003041 if (what & layer_state_t::eRelativeLayerChanged) {
chaviw64f7b422017-07-12 10:31:58 -07003042 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carrdb66e622017-04-10 16:55:57 -07003043 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z)) {
chaviw64f7b422017-07-12 10:31:58 -07003044 mCurrentState.layersSortedByZ.removeAt(idx);
3045 mCurrentState.layersSortedByZ.add(layer);
Robert Carrdb66e622017-04-10 16:55:57 -07003046 flags |= eTransactionNeeded|eTraversalNeeded;
3047 }
3048 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003049 if (what & layer_state_t::eSizeChanged) {
3050 if (layer->setSize(s.w, s.h)) {
3051 flags |= eTraversalNeeded;
3052 }
3053 }
3054 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003055 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003056 flags |= eTraversalNeeded;
3057 }
3058 if (what & layer_state_t::eMatrixChanged) {
3059 if (layer->setMatrix(s.matrix))
3060 flags |= eTraversalNeeded;
3061 }
3062 if (what & layer_state_t::eTransparentRegionChanged) {
3063 if (layer->setTransparentRegionHint(s.transparentRegion))
3064 flags |= eTraversalNeeded;
3065 }
Dan Stoza23116082015-06-18 14:58:39 -07003066 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003067 if (layer->setFlags(s.flags, s.mask))
3068 flags |= eTraversalNeeded;
3069 }
3070 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07003071 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003072 flags |= eTraversalNeeded;
3073 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003074 if (what & layer_state_t::eFinalCropChanged) {
Robert Carr8d5227b2017-03-16 15:41:03 -07003075 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003076 flags |= eTraversalNeeded;
3077 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003078 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003079 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003080 // We only allow setting layer stacks for top level layers,
3081 // everything else inherits layer stack from its parent.
3082 if (layer->hasParent()) {
3083 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3084 layer->getName().string());
3085 } else if (idx < 0) {
3086 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3087 "that also does not appear in the top level layer list. Something"
3088 " has gone wrong.", layer->getName().string());
3089 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003090 mCurrentState.layersSortedByZ.removeAt(idx);
3091 mCurrentState.layersSortedByZ.add(layer);
3092 // we need traversal (state changed)
3093 // AND transaction (list changed)
3094 flags |= eTransactionNeeded|eTraversalNeeded;
3095 }
3096 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003097 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08003098 if (s.barrierHandle != nullptr) {
3099 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3100 } else if (s.barrierGbp != nullptr) {
3101 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3102 if (authenticateSurfaceTextureLocked(gbp)) {
3103 const auto& otherLayer =
3104 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3105 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3106 } else {
3107 ALOGE("Attempt to defer transaction to to an"
3108 " unrecognized GraphicBufferProducer");
3109 }
3110 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003111 // We don't trigger a traversal here because if no other state is
3112 // changed, we don't want this to cause any more work
3113 }
Robert Carr1db73f62016-12-21 12:58:51 -08003114 if (what & layer_state_t::eReparentChildren) {
3115 if (layer->reparentChildren(s.reparentHandle)) {
3116 flags |= eTransactionNeeded|eTraversalNeeded;
3117 }
3118 }
Robert Carr9524cb32017-02-13 11:32:32 -08003119 if (what & layer_state_t::eDetachChildren) {
3120 layer->detachChildren();
3121 }
Robert Carrc3574f72016-03-24 12:19:32 -07003122 if (what & layer_state_t::eOverrideScalingModeChanged) {
3123 layer->setOverrideScalingMode(s.overrideScalingMode);
3124 // We don't trigger a traversal here because if no other state is
3125 // changed, we don't want this to cause any more work
3126 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003127 }
3128 return flags;
3129}
3130
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003131status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003132 const String8& name,
3133 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003134 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003135 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3136 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003137{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003138 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003139 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003140 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003141 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003142 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003143
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003144 status_t result = NO_ERROR;
3145
3146 sp<Layer> layer;
3147
Cody Northropbc755282017-03-31 12:00:08 -06003148 String8 uniqueName = getUniqueLayerName(name);
3149
Mathias Agopian3165cc22012-08-08 19:42:09 -07003150 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3151 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003152 result = createNormalLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003153 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003154 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003155 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07003156 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003157 result = createDimLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003158 uniqueName, w, h, flags,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003159 handle, gbp, &layer);
3160 break;
3161 default:
3162 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003163 break;
3164 }
3165
Dan Stoza7d89d062015-04-30 13:29:25 -07003166 if (result != NO_ERROR) {
3167 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003168 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003169
Chia-I Wuab0c3192017-08-01 11:29:00 -07003170 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3171 // TODO b/64227542
3172 if (windowType == 441731) {
3173 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3174 layer->setPrimaryDisplayOnly();
3175 }
3176
Albert Chaulk479c60c2017-01-27 14:21:34 -05003177 layer->setInfo(windowType, ownerUid);
3178
Robert Carr1f0a16a2016-10-24 16:27:39 -07003179 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003180 if (result != NO_ERROR) {
3181 return result;
3182 }
Irvelffc9efc2016-07-27 15:16:37 -07003183 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003184
3185 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003186 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003187}
3188
Cody Northropbc755282017-03-31 12:00:08 -06003189String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3190{
3191 bool matchFound = true;
3192 uint32_t dupeCounter = 0;
3193
3194 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3195 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3196
3197 // Loop over layers until we're sure there is no matching name
3198 while (matchFound) {
3199 matchFound = false;
3200 mDrawingState.traverseInZOrder([&](Layer* layer) {
3201 if (layer->getName() == uniqueName) {
3202 matchFound = true;
3203 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3204 }
3205 });
3206 }
3207
3208 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3209
3210 return uniqueName;
3211}
3212
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003213status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
3214 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3215 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003216{
3217 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003218 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003219 case PIXEL_FORMAT_TRANSPARENT:
3220 case PIXEL_FORMAT_TRANSLUCENT:
3221 format = PIXEL_FORMAT_RGBA_8888;
3222 break;
3223 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003224 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003225 break;
3226 }
3227
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003228 *outLayer = new Layer(this, client, name, w, h, flags);
3229 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
3230 if (err == NO_ERROR) {
3231 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003232 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003233 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003234
3235 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3236 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003237}
3238
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003239status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
3240 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3241 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003242{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003243 *outLayer = new LayerDim(this, client, name, w, h, flags);
3244 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003245 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003246 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003247}
3248
Mathias Agopianac9fa422013-02-11 16:40:36 -08003249status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003250{
Robert Carr9524cb32017-02-13 11:32:32 -08003251 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003252 status_t err = NO_ERROR;
3253 sp<Layer> l(client->getLayerUser(handle));
3254 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003255 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003256 err = removeLayer(l);
3257 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3258 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003259 }
3260 return err;
3261}
3262
Mathias Agopian13127d82013-03-05 17:47:11 -08003263status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003264{
Mathias Agopian67106042013-03-14 19:18:13 -07003265 // called by ~LayerCleaner() when all references to the IBinder (handle)
3266 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003267 sp<Layer> l = layer.promote();
3268 if (l == nullptr) {
3269 // The layer has already been removed, carry on
3270 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003271 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003272 // If we have a parent, then we can continue to live as long as it does.
3273 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003274}
3275
Mathias Agopianb60314a2012-04-10 22:09:54 -07003276// ---------------------------------------------------------------------------
3277
Andy McFadden13a082e2012-08-24 10:16:42 -07003278void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003279 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003280 Vector<ComposerState> state;
3281 Vector<DisplayState> displays;
3282 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003283 d.what = DisplayState::eDisplayProjectionChanged |
3284 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003285 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003286 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003287 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003288 d.frame.makeInvalid();
3289 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003290 d.width = 0;
3291 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003292 displays.add(d);
3293 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003294 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3295 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003296
Dan Stoza9e56aa02015-11-02 13:00:03 -08003297 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3298 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003299 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003300
Brian Andersond0010582017-03-07 13:20:31 -08003301 // Use phase of 0 since phase is not known.
3302 // Use latency of 0, which will snap to the ideal latency.
3303 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003304}
3305
3306void SurfaceFlinger::initializeDisplays() {
3307 class MessageScreenInitialized : public MessageBase {
3308 SurfaceFlinger* flinger;
3309 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003310 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003311 virtual bool handler() {
3312 flinger->onInitializeDisplays();
3313 return true;
3314 }
3315 };
3316 sp<MessageBase> msg = new MessageScreenInitialized(this);
3317 postMessageAsync(msg); // we may be called from main thread, use async message
3318}
3319
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003320void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003321 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003322 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3323 this);
3324 int32_t type = hw->getDisplayType();
3325 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003326
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003327 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003328 return;
3329 }
3330
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003331 hw->setPowerMode(mode);
3332 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3333 ALOGW("Trying to set power mode for virtual display");
3334 return;
3335 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003336
Irvelffc9efc2016-07-27 15:16:37 -07003337 if (mInterceptor.isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003338 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003339 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3340 if (idx < 0) {
3341 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3342 return;
3343 }
3344 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3345 }
3346
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003347 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003348 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003349 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003350 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3351 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003352 // FIXME: eventthread only knows about the main display right now
3353 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003354 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003355 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003356
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003357 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003358 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003359 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003360
3361 struct sched_param param = {0};
3362 param.sched_priority = 1;
3363 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3364 ALOGW("Couldn't set SCHED_FIFO on display on");
3365 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003366 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003367 // Turn off the display
3368 struct sched_param param = {0};
3369 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3370 ALOGW("Couldn't set SCHED_OTHER on display off");
3371 }
3372
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003373 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003374 disableHardwareVsync(true); // also cancels any in-progress resync
3375
Mathias Agopiancde87a32012-09-13 14:09:01 -07003376 // FIXME: eventthread only knows about the main display right now
3377 mEventThread->onScreenReleased();
3378 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003379
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003380 getHwComposer().setPowerMode(type, mode);
3381 mVisibleRegionsDirty = true;
3382 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003383 } else if (mode == HWC_POWER_MODE_DOZE ||
3384 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003385 // Update display while dozing
3386 getHwComposer().setPowerMode(type, mode);
3387 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3388 // FIXME: eventthread only knows about the main display right now
3389 mEventThread->onScreenAcquired();
3390 resyncToHardwareVsync(true);
3391 }
3392 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3393 // Leave display going to doze
3394 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3395 disableHardwareVsync(true); // also cancels any in-progress resync
3396 // FIXME: eventthread only knows about the main display right now
3397 mEventThread->onScreenReleased();
3398 }
3399 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003400 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003401 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003402 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003403 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003404}
3405
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003406void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3407 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003408 SurfaceFlinger& mFlinger;
3409 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003410 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003411 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003412 MessageSetPowerMode(SurfaceFlinger& flinger,
3413 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3414 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003415 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003416 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003417 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003418 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003419 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003420 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003421 ALOGW("Attempt to set power mode = %d for virtual display",
3422 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003423 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003424 mFlinger.setPowerModeInternal(
3425 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003426 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003427 return true;
3428 }
3429 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003430 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003431 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003432}
3433
3434// ---------------------------------------------------------------------------
3435
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003436status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3437{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003438 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003439
Mathias Agopianbd115332013-04-18 16:41:04 -07003440 IPCThreadState* ipc = IPCThreadState::self();
3441 const int pid = ipc->getCallingPid();
3442 const int uid = ipc->getCallingUid();
3443 if ((uid != AID_SHELL) &&
3444 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003445 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003446 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003447 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003448 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003449 // (this would indicate SF is stuck, but we want to be able to
3450 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003451 status_t err = mStateLock.timedLock(s2ns(1));
3452 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003453 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003454 result.appendFormat(
3455 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3456 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003457 }
3458
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003459 bool dumpAll = true;
3460 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003461 size_t numArgs = args.size();
3462 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003463 if ((index < numArgs) &&
3464 (args[index] == String16("--list"))) {
3465 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003466 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003467 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003468 }
3469
3470 if ((index < numArgs) &&
3471 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003472 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003473 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003474 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003475 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003476
3477 if ((index < numArgs) &&
3478 (args[index] == String16("--latency-clear"))) {
3479 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003480 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003481 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003482 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003483
3484 if ((index < numArgs) &&
3485 (args[index] == String16("--dispsync"))) {
3486 index++;
3487 mPrimaryDispSync.dump(result);
3488 dumpAll = false;
3489 }
Dan Stozab90cf072015-03-05 11:05:59 -08003490
3491 if ((index < numArgs) &&
3492 (args[index] == String16("--static-screen"))) {
3493 index++;
3494 dumpStaticScreenStats(result);
3495 dumpAll = false;
3496 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003497
3498 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003499 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003500 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003501 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003502 dumpAll = false;
3503 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003504
3505 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3506 index++;
3507 dumpWideColorInfo(result);
3508 dumpAll = false;
3509 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003510 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003511
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003512 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003513 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003514 }
3515
Mathias Agopian9795c422009-08-26 16:36:26 -07003516 if (locked) {
3517 mStateLock.unlock();
3518 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003519 }
3520 write(fd, result.string(), result.size());
3521 return NO_ERROR;
3522}
3523
Dan Stozac7014012014-02-14 15:03:43 -08003524void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3525 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003526{
Robert Carr2047fae2016-11-28 14:09:09 -08003527 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003528 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003529 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003530}
3531
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003532void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003533 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003534{
3535 String8 name;
3536 if (index < args.size()) {
3537 name = String8(args[index]);
3538 index++;
3539 }
3540
Dan Stoza9e56aa02015-11-02 13:00:03 -08003541 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3542 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003543 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003544
3545 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003546 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003547 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003548 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003549 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003550 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003551 }
Robert Carr2047fae2016-11-28 14:09:09 -08003552 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003553 }
3554}
3555
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003556void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003557 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003558{
3559 String8 name;
3560 if (index < args.size()) {
3561 name = String8(args[index]);
3562 index++;
3563 }
3564
Robert Carr2047fae2016-11-28 14:09:09 -08003565 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003566 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003567 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003568 }
Robert Carr2047fae2016-11-28 14:09:09 -08003569 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003570
Svetoslavd85084b2014-03-20 10:28:31 -07003571 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003572}
3573
Jamie Gennis6547ff42013-07-16 20:12:42 -07003574// This should only be called from the main thread. Otherwise it would need
3575// the lock and should use mCurrentState rather than mDrawingState.
3576void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003577 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003578 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003579 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003580
3581 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3582}
3583
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003584void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003585{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003586 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003587 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3588
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003589 if (isLayerTripleBufferingDisabled())
3590 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003591
3592 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003593 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003594 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003595 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003596 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3597 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003598 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003599}
3600
Dan Stozab90cf072015-03-05 11:05:59 -08003601void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3602{
3603 result.appendFormat("Static screen stats:\n");
3604 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3605 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3606 float percent = 100.0f *
3607 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3608 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3609 b + 1, bucketTimeSec, percent);
3610 }
3611 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3612 float percent = 100.0f *
3613 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3614 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3615 NUM_BUCKETS - 1, bucketTimeSec, percent);
3616}
3617
Dan Stozae77c7662016-05-13 11:37:28 -07003618void SurfaceFlinger::recordBufferingStats(const char* layerName,
3619 std::vector<OccupancyTracker::Segment>&& history) {
3620 Mutex::Autolock lock(mBufferingStatsMutex);
3621 auto& stats = mBufferingStats[layerName];
3622 for (const auto& segment : history) {
3623 if (!segment.usedThirdBuffer) {
3624 stats.twoBufferTime += segment.totalTime;
3625 }
3626 if (segment.occupancyAverage < 1.0f) {
3627 stats.doubleBufferedTime += segment.totalTime;
3628 } else if (segment.occupancyAverage < 2.0f) {
3629 stats.tripleBufferedTime += segment.totalTime;
3630 }
3631 ++stats.numSegments;
3632 stats.totalTime += segment.totalTime;
3633 }
3634}
3635
Brian Andersond6927fb2016-07-23 23:37:30 -07003636void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3637 result.appendFormat("Layer frame timestamps:\n");
3638
3639 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3640 const size_t count = currentLayers.size();
3641 for (size_t i=0 ; i<count ; i++) {
3642 currentLayers[i]->dumpFrameEvents(result);
3643 }
3644}
3645
Dan Stozae77c7662016-05-13 11:37:28 -07003646void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3647 result.append("Buffering stats:\n");
3648 result.append(" [Layer name] <Active time> <Two buffer> "
3649 "<Double buffered> <Triple buffered>\n");
3650 Mutex::Autolock lock(mBufferingStatsMutex);
3651 typedef std::tuple<std::string, float, float, float> BufferTuple;
3652 std::map<float, BufferTuple, std::greater<float>> sorted;
3653 for (const auto& statsPair : mBufferingStats) {
3654 const char* name = statsPair.first.c_str();
3655 const BufferingStats& stats = statsPair.second;
3656 if (stats.numSegments == 0) {
3657 continue;
3658 }
3659 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3660 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3661 stats.totalTime;
3662 float doubleBufferRatio = static_cast<float>(
3663 stats.doubleBufferedTime) / stats.totalTime;
3664 float tripleBufferRatio = static_cast<float>(
3665 stats.tripleBufferedTime) / stats.totalTime;
3666 sorted.insert({activeTime, {name, twoBufferRatio,
3667 doubleBufferRatio, tripleBufferRatio}});
3668 }
3669 for (const auto& sortedPair : sorted) {
3670 float activeTime = sortedPair.first;
3671 const BufferTuple& values = sortedPair.second;
3672 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3673 std::get<0>(values).c_str(), activeTime,
3674 std::get<1>(values), std::get<2>(values),
3675 std::get<3>(values));
3676 }
3677 result.append("\n");
3678}
3679
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003680void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3681 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
3682
3683 // TODO: print out if wide-color mode is active or not
3684
3685 for (size_t d = 0; d < mDisplays.size(); d++) {
3686 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3687 int32_t hwcId = displayDevice->getHwcDisplayId();
3688 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3689 continue;
3690 }
3691
3692 result.appendFormat("Display %d color modes:\n", hwcId);
3693 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3694 for (auto&& mode : modes) {
3695 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3696 }
3697
3698 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3699 result.appendFormat(" Current color mode: %s (%d)\n",
3700 decodeColorMode(currentMode).c_str(), currentMode);
3701 }
3702 result.append("\n");
3703}
3704
Mathias Agopian74d211a2013-04-22 16:55:35 +02003705void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3706 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003707{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003708 bool colorize = false;
3709 if (index < args.size()
3710 && (args[index] == String16("--color"))) {
3711 colorize = true;
3712 index++;
3713 }
3714
3715 Colorizer colorizer(colorize);
3716
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003717 // figure out if we're stuck somewhere
3718 const nsecs_t now = systemTime();
3719 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3720 const nsecs_t inTransaction(mDebugInTransaction);
3721 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3722 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3723
3724 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003725 * Dump library configuration.
3726 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003727
3728 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003729 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003730 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003731 appendSfConfigString(result);
3732 appendUiConfigString(result);
3733 appendGuiConfigString(result);
3734 result.append("\n");
3735
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003736 result.append("\nWide-Color information:\n");
3737 dumpWideColorInfo(result);
3738
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003739 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003740 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003741 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003742 result.append(SyncFeatures::getInstance().toString());
3743 result.append("\n");
3744
Dan Stoza9e56aa02015-11-02 13:00:03 -08003745 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3746
Andy McFadden41d67d72014-04-25 16:58:34 -07003747 colorizer.bold(result);
3748 result.append("DispSync configuration: ");
3749 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003750 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003751 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003752 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003753 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003754 result.append("\n");
3755
Dan Stozab90cf072015-03-05 11:05:59 -08003756 // Dump static screen stats
3757 result.append("\n");
3758 dumpStaticScreenStats(result);
3759 result.append("\n");
3760
Dan Stozae77c7662016-05-13 11:37:28 -07003761 dumpBufferingStats(result);
3762
Andy McFadden4803b742012-09-24 19:07:20 -07003763 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003764 * Dump the visible layer list
3765 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003766 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003767 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003768 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003769 mCurrentState.traverseInZOrder([&](Layer* layer) {
Kalle Raitaa099a242017-01-11 11:17:29 -08003770 result.append(to_string(layer->getLayerDebugInfo()).c_str());
Robert Carr2047fae2016-11-28 14:09:09 -08003771 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003772
3773 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003774 * Dump Display state
3775 */
3776
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003777 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003778 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003779 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003780 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3781 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003782 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003783 }
3784
3785 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003786 * Dump SurfaceFlinger global state
3787 */
3788
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003789 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003790 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003791 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003792
Mathias Agopian888c8222012-08-04 21:10:38 -07003793 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003794 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003795
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003796 colorizer.bold(result);
3797 result.appendFormat("EGL implementation : %s\n",
3798 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3799 colorizer.reset(result);
3800 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003801 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003802
Mathias Agopian875d8e12013-06-07 15:35:48 -07003803 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003804
Mathias Agopian42977342012-08-05 00:40:46 -07003805 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003806 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3807 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003808 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003809 " last eglSwapBuffers() time: %f us\n"
3810 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003811 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003812 " refresh-rate : %f fps\n"
3813 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003814 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003815 " gpu_to_cpu_unsupported : %d\n"
3816 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003817 mLastSwapBufferTime/1000.0,
3818 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003819 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003820 1e9 / activeConfig->getVsyncPeriod(),
3821 activeConfig->getDpiX(),
3822 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003823 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003824
Mathias Agopian74d211a2013-04-22 16:55:35 +02003825 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003826 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003827
Mathias Agopian74d211a2013-04-22 16:55:35 +02003828 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003829 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003830
3831 /*
3832 * VSYNC state
3833 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003834 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003835 result.append("\n");
3836
3837 /*
3838 * HWC layer minidump
3839 */
3840 for (size_t d = 0; d < mDisplays.size(); d++) {
3841 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3842 int32_t hwcId = displayDevice->getHwcDisplayId();
3843 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3844 continue;
3845 }
3846
3847 result.appendFormat("Display %d HWC layers:\n", hwcId);
3848 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003849 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003850 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003851 });
Dan Stozae22aec72016-08-01 13:20:59 -07003852 result.append("\n");
3853 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003854
3855 /*
3856 * Dump HWComposer state
3857 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003858 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003859 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003860 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003861 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003862 result.appendFormat(" h/w composer %s\n",
3863 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003864 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003865
3866 /*
3867 * Dump gralloc state
3868 */
3869 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3870 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07003871
3872 /*
3873 * Dump VrFlinger state if in use.
3874 */
3875 if (mVrFlingerRequestsDisplay && mVrFlinger) {
3876 result.append("VrFlinger state:\n");
3877 result.append(mVrFlinger->Dump().c_str());
3878 result.append("\n");
3879 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003880}
3881
Mathias Agopian13127d82013-03-05 17:47:11 -08003882const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003883SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003884 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003885 wp<IBinder> dpy;
3886 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3887 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3888 dpy = mDisplays.keyAt(i);
3889 break;
3890 }
3891 }
3892 if (dpy == NULL) {
3893 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3894 // Just use the primary display so we have something to return
3895 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3896 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003897 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003898}
3899
Keun young Park63f165f2012-08-31 10:53:36 -07003900bool SurfaceFlinger::startDdmConnection()
3901{
3902 void* libddmconnection_dso =
3903 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3904 if (!libddmconnection_dso) {
3905 return false;
3906 }
3907 void (*DdmConnection_start)(const char* name);
3908 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003909 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003910 if (!DdmConnection_start) {
3911 dlclose(libddmconnection_dso);
3912 return false;
3913 }
3914 (*DdmConnection_start)(getServiceName());
3915 return true;
3916}
3917
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003918status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003919 switch (code) {
3920 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003921 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003922 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003923 case CLEAR_ANIMATION_FRAME_STATS:
3924 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003925 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003926 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003927 {
3928 // codes that require permission check
3929 IPCThreadState* ipc = IPCThreadState::self();
3930 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003931 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003932 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003933 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003934 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003935 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003936 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003937 break;
3938 }
Robert Carr1db73f62016-12-21 12:58:51 -08003939 /*
3940 * Calling setTransactionState is safe, because you need to have been
3941 * granted a reference to Client* and Handle* to do anything with it.
3942 *
3943 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3944 */
3945 case SET_TRANSACTION_STATE:
3946 case CREATE_SCOPED_CONNECTION:
3947 {
3948 return OK;
3949 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003950 case CAPTURE_SCREEN:
3951 {
3952 // codes that require permission check
3953 IPCThreadState* ipc = IPCThreadState::self();
3954 const int pid = ipc->getCallingPid();
3955 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003956 if ((uid != AID_GRAPHICS) &&
3957 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003958 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003959 return PERMISSION_DENIED;
3960 }
3961 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003962 }
3963 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003964 return OK;
3965}
3966
3967status_t SurfaceFlinger::onTransact(
3968 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3969{
3970 status_t credentialCheck = CheckTransactCodeCredentials(code);
3971 if (credentialCheck != OK) {
3972 return credentialCheck;
3973 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003974
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003975 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3976 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003977 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07003978 IPCThreadState* ipc = IPCThreadState::self();
3979 const int uid = ipc->getCallingUid();
3980 if (CC_UNLIKELY(uid != AID_SYSTEM
3981 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003982 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003983 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003984 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003985 return PERMISSION_DENIED;
3986 }
3987 int n;
3988 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003989 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003990 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003991 return NO_ERROR;
3992 case 1002: // SHOW_UPDATES
3993 n = data.readInt32();
3994 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003995 invalidateHwcGeometry();
3996 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003997 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003998 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003999 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004000 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004001 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004002 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07004003 setTransactionFlags(
4004 eTransactionNeeded|
4005 eDisplayTransactionNeeded|
4006 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004007 return NO_ERROR;
4008 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004009 case 1006:{ // send empty update
4010 signalRefresh();
4011 return NO_ERROR;
4012 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004013 case 1008: // toggle use of hw composer
4014 n = data.readInt32();
4015 mDebugDisableHWC = n ? 1 : 0;
4016 invalidateHwcGeometry();
4017 repaintEverything();
4018 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004019 case 1009: // toggle use of transform hint
4020 n = data.readInt32();
4021 mDebugDisableTransformHint = n ? 1 : 0;
4022 invalidateHwcGeometry();
4023 repaintEverything();
4024 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004025 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004026 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004027 reply->writeInt32(0);
4028 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004029 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004030 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004031 return NO_ERROR;
4032 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004033 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004034 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004035 return NO_ERROR;
4036 }
4037 case 1014: {
4038 // daltonize
4039 n = data.readInt32();
4040 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004041 case 1:
4042 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4043 break;
4044 case 2:
4045 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4046 break;
4047 case 3:
4048 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4049 break;
4050 default:
4051 mDaltonizer.setType(ColorBlindnessType::None);
4052 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004053 }
4054 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004055 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004056 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004057 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004058 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004059 invalidateHwcGeometry();
4060 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004061 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004062 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004063 case 1015: {
4064 // apply a color matrix
4065 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004066 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004067 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004068 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004069 for (size_t j = 0; j < 4; j++) {
4070 mColorMatrix[i][j] = data.readFloat();
4071 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004072 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004073 } else {
4074 mColorMatrix = mat4();
4075 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004076
4077 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4078 // the division by w in the fragment shader
4079 float4 lastRow(transpose(mColorMatrix)[3]);
4080 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4081 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4082 }
4083
Alan Viverette9c5a3332013-09-12 20:04:35 -07004084 invalidateHwcGeometry();
4085 repaintEverything();
4086 return NO_ERROR;
4087 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004088 // This is an experimental interface
4089 // Needs to be shifted to proper binder interface when we productize
4090 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004091 n = data.readInt32();
4092 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004093 return NO_ERROR;
4094 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004095 case 1017: {
4096 n = data.readInt32();
4097 mForceFullDamage = static_cast<bool>(n);
4098 return NO_ERROR;
4099 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004100 case 1018: { // Modify Choreographer's phase offset
4101 n = data.readInt32();
4102 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4103 return NO_ERROR;
4104 }
4105 case 1019: { // Modify SurfaceFlinger's phase offset
4106 n = data.readInt32();
4107 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4108 return NO_ERROR;
4109 }
Irvel468051e2016-06-13 16:44:44 -07004110 case 1020: { // Layer updates interceptor
4111 n = data.readInt32();
4112 if (n) {
4113 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004114 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004115 }
4116 else{
4117 ALOGV("Interceptor disabled");
4118 mInterceptor.disable();
4119 }
4120 return NO_ERROR;
4121 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004122 case 1021: { // Disable HWC virtual displays
4123 n = data.readInt32();
4124 mUseHwcVirtualDisplays = !n;
4125 return NO_ERROR;
4126 }
Romain Guy0147a172017-06-01 13:53:56 -07004127 case 1022: { // Set saturation boost
4128 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4129
4130 invalidateHwcGeometry();
4131 repaintEverything();
4132 return NO_ERROR;
4133 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004134 }
4135 }
4136 return err;
4137}
4138
Mathias Agopian53331da2011-08-22 21:44:41 -07004139void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004140 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004141 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004142}
4143
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004144// Checks that the requested width and height are valid and updates them to the display dimensions
4145// if they are set to 0
4146static status_t updateDimensionsLocked(const sp<const DisplayDevice>& displayDevice,
4147 Transform::orientation_flags rotation,
4148 uint32_t* requestedWidth, uint32_t* requestedHeight) {
4149 // get screen geometry
4150 uint32_t displayWidth = displayDevice->getWidth();
4151 uint32_t displayHeight = displayDevice->getHeight();
Mathias Agopian9daa5c92010-10-12 16:05:48 -07004152
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004153 if (rotation & Transform::ROT_90) {
4154 std::swap(displayWidth, displayHeight);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004155 }
4156
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004157 if ((*requestedWidth > displayWidth) || (*requestedHeight > displayHeight)) {
4158 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4159 *requestedWidth, *requestedHeight, displayWidth, displayHeight);
4160 return BAD_VALUE;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004161 }
4162
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004163 if (*requestedWidth == 0) {
4164 *requestedWidth = displayWidth;
4165 }
4166 if (*requestedHeight == 0) {
4167 *requestedHeight = displayHeight;
4168 }
4169
4170 return NO_ERROR;
4171}
4172
4173// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4174class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004175public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004176 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4177 ~WindowDisconnector() {
4178 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004179 }
4180
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004181private:
4182 ANativeWindow* mWindow;
4183 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004184};
4185
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004186static status_t getWindowBuffer(ANativeWindow* window, uint32_t requestedWidth,
4187 uint32_t requestedHeight, bool hasWideColorDisplay,
4188 bool renderEngineUsesWideColor, ANativeWindowBuffer** outBuffer) {
4189 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4190 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4191
4192 int err = 0;
4193 err = native_window_set_buffers_dimensions(window, requestedWidth, requestedHeight);
4194 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
4195 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4196 err |= native_window_set_usage(window, usage);
4197
4198 if (hasWideColorDisplay) {
4199 err |= native_window_set_buffers_data_space(window,
4200 renderEngineUsesWideColor
4201 ? HAL_DATASPACE_DISPLAY_P3
4202 : HAL_DATASPACE_V0_SRGB);
4203 }
4204
4205 if (err != NO_ERROR) {
4206 return BAD_VALUE;
4207 }
4208
4209 /* TODO: Once we have the sync framework everywhere this can use
4210 * server-side waits on the fence that dequeueBuffer returns.
4211 */
4212 err = native_window_dequeue_buffer_and_wait(window, outBuffer);
4213 if (err != NO_ERROR) {
4214 return err;
4215 }
4216
4217 return NO_ERROR;
4218}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004219
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004220status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4221 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004222 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004223 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004224 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004225 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004226
4227 if (CC_UNLIKELY(display == 0))
4228 return BAD_VALUE;
4229
4230 if (CC_UNLIKELY(producer == 0))
4231 return BAD_VALUE;
4232
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004233 // if we have secure windows on this display, never allow the screen capture
4234 // unless the producer interface is local (i.e.: we can take a screenshot for
4235 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004236 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004237
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004238 // Convert to surfaceflinger's internal rotation type.
4239 Transform::orientation_flags rotationFlags;
4240 switch (rotation) {
4241 case ISurfaceComposer::eRotateNone:
4242 rotationFlags = Transform::ROT_0;
4243 break;
4244 case ISurfaceComposer::eRotate90:
4245 rotationFlags = Transform::ROT_90;
4246 break;
4247 case ISurfaceComposer::eRotate180:
4248 rotationFlags = Transform::ROT_180;
4249 break;
4250 case ISurfaceComposer::eRotate270:
4251 rotationFlags = Transform::ROT_270;
4252 break;
4253 default:
4254 rotationFlags = Transform::ROT_0;
4255 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
4256 break;
4257 }
4258
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004259 { // Autolock scope
4260 Mutex::Autolock lock(mStateLock);
4261 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
4262 updateDimensionsLocked(displayDevice, rotationFlags, &reqWidth, &reqHeight);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004263 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004264
4265 // create a surface (because we're a producer, and we need to
4266 // dequeue/queue a buffer)
4267 sp<Surface> surface = new Surface(producer, false);
4268
4269 // Put the screenshot Surface into async mode so that
4270 // Layer::headFenceHasSignaled will always return true and we'll latch the
4271 // first buffer regardless of whether or not its acquire fence has
4272 // signaled. This is needed to avoid a race condition in the rotation
4273 // animation. See b/30209608
4274 surface->setAsyncMode(true);
4275
4276 ANativeWindow* window = surface.get();
4277
4278 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4279 if (result != NO_ERROR) {
4280 return result;
4281 }
4282 WindowDisconnector disconnector(window, NATIVE_WINDOW_API_EGL);
4283
4284 ANativeWindowBuffer* buffer = nullptr;
4285 result = getWindowBuffer(window, reqWidth, reqHeight, hasWideColorDisplay,
4286 getRenderEngine().usesWideColor(), &buffer);
4287 if (result != NO_ERROR) {
4288 return result;
4289 }
4290
4291 // This mutex protects syncFd and captureResult for communication of the return values from the
4292 // main thread back to this Binder thread
4293 std::mutex captureMutex;
4294 std::condition_variable captureCondition;
4295 std::unique_lock<std::mutex> captureLock(captureMutex);
4296 int syncFd = -1;
4297 std::optional<status_t> captureResult;
4298
4299 sp<LambdaMessage> message = new LambdaMessage([&]() {
4300 // If there is a refresh pending, bug out early and tell the binder thread to try again
4301 // after the refresh.
4302 if (mRefreshPending) {
4303 ATRACE_NAME("Skipping screenshot for now");
4304 std::unique_lock<std::mutex> captureLock(captureMutex);
4305 captureResult = std::make_optional<status_t>(EAGAIN);
4306 captureCondition.notify_one();
4307 return;
4308 }
4309
4310 status_t result = NO_ERROR;
4311 int fd = -1;
4312 {
4313 Mutex::Autolock _l(mStateLock);
4314 sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4315 result = captureScreenImplLocked(device, buffer, sourceCrop, reqWidth, reqHeight,
4316 minLayerZ, maxLayerZ, useIdentityTransform,
4317 rotationFlags, isLocalScreenshot, &fd);
4318 }
4319
4320 {
4321 std::unique_lock<std::mutex> captureLock(captureMutex);
4322 syncFd = fd;
4323 captureResult = std::make_optional<status_t>(result);
4324 captureCondition.notify_one();
4325 }
4326 });
4327
4328 result = postMessageAsync(message);
4329 if (result == NO_ERROR) {
4330 captureCondition.wait(captureLock, [&]() { return captureResult; });
4331 while (*captureResult == EAGAIN) {
4332 captureResult.reset();
4333 result = postMessageAsync(message);
4334 if (result != NO_ERROR) {
4335 return result;
4336 }
4337 captureCondition.wait(captureLock, [&]() { return captureResult; });
4338 }
4339 result = *captureResult;
4340 }
4341
4342 if (result == NO_ERROR) {
4343 // queueBuffer takes ownership of syncFd
4344 result = window->queueBuffer(window, buffer, syncFd);
4345 }
4346
4347 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004348}
4349
Mathias Agopian180f10d2013-04-10 22:55:41 -07004350
4351void SurfaceFlinger::renderScreenImplLocked(
4352 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07004353 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004354 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004355 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07004356{
4357 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07004358 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004359
4360 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08004361 const int32_t hw_w = hw->getWidth();
4362 const int32_t hw_h = hw->getHeight();
4363 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07004364 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004365
Dan Stozac1879002014-05-22 15:59:05 -07004366 // if a default or invalid sourceCrop is passed in, set reasonable values
4367 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
4368 !sourceCrop.isValid()) {
4369 sourceCrop.setLeftTop(Point(0, 0));
4370 sourceCrop.setRightBottom(Point(hw_w, hw_h));
4371 }
4372
4373 // ensure that sourceCrop is inside screen
4374 if (sourceCrop.left < 0) {
4375 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4376 }
Dan Stozabe31f442014-06-11 11:20:54 -07004377 if (sourceCrop.right > hw_w) {
4378 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07004379 }
4380 if (sourceCrop.top < 0) {
4381 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4382 }
Dan Stozabe31f442014-06-11 11:20:54 -07004383 if (sourceCrop.bottom > hw_h) {
4384 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004385 }
4386
Romain Guy88d37dd2017-05-26 17:57:05 -07004387#ifdef USE_HWC2
4388 engine.setWideColor(hw->getWideColorSupport());
4389 engine.setColorMode(hw->getActiveColorMode());
4390#endif
4391
Mathias Agopian180f10d2013-04-10 22:55:41 -07004392 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004393 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004394
4395 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004396 engine.setViewportAndProjection(
4397 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004398 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004399
4400 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004401 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004402
Robert Carr1f0a16a2016-10-24 16:27:39 -07004403 // We loop through the first level of layers without traversing,
4404 // as we need to interpret min/max layer Z in the top level Z space.
4405 for (const auto& layer : mDrawingState.layersSortedByZ) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07004406 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004407 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004408 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004409 const Layer::State& state(layer->getDrawingState());
4410 if (state.z < minLayerZ || state.z > maxLayerZ) {
4411 continue;
4412 }
Dan Stoza412903f2017-04-27 13:42:17 -07004413 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004414 if (!layer->isVisible()) {
4415 return;
4416 }
4417 if (filtering) layer->setFiltering(true);
4418 layer->draw(hw, useIdentityTransform);
4419 if (filtering) layer->setFiltering(false);
4420 });
4421 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004422
Mathias Agopian931bda12013-08-28 18:11:46 -07004423 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004424}
4425
Dan Stozaabcda352017-06-01 14:37:39 -07004426// A simple RAII class that holds an EGLImage and destroys it either:
4427// a) When the destroy() method is called
4428// b) When the object goes out of scope
4429class ImageHolder {
4430public:
4431 ImageHolder(EGLDisplay display, EGLImageKHR image) : mDisplay(display), mImage(image) {}
4432 ~ImageHolder() { destroy(); }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004433
Dan Stozaabcda352017-06-01 14:37:39 -07004434 void destroy() {
4435 if (mImage != EGL_NO_IMAGE_KHR) {
4436 eglDestroyImageKHR(mDisplay, mImage);
4437 mImage = EGL_NO_IMAGE_KHR;
4438 }
4439 }
4440
4441private:
4442 const EGLDisplay mDisplay;
4443 EGLImageKHR mImage;
4444};
4445
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004446status_t SurfaceFlinger::captureScreenImplLocked(const sp<const DisplayDevice>& hw,
4447 ANativeWindowBuffer* buffer, Rect sourceCrop,
4448 uint32_t reqWidth, uint32_t reqHeight,
4449 int32_t minLayerZ, int32_t maxLayerZ,
4450 bool useIdentityTransform,
4451 Transform::orientation_flags rotation,
4452 bool isLocalScreenshot, int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004453 ATRACE_CALL();
4454
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004455 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004456 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004457 const Layer::State& state(layer->getDrawingState());
Chia-I Wufc0b9112017-08-07 15:27:49 -07004458 if (!layer->belongsToDisplay(hw->getLayerStack(), false) ||
Robert Carr1f0a16a2016-10-24 16:27:39 -07004459 (state.z < minLayerZ || state.z > maxLayerZ)) {
4460 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004461 }
Dan Stoza412903f2017-04-27 13:42:17 -07004462 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer *layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004463 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4464 layer->isSecure());
4465 });
4466 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004467
4468 if (!isLocalScreenshot && secureLayerIsVisible) {
4469 ALOGW("FB is protected: PERMISSION_DENIED");
4470 return PERMISSION_DENIED;
4471 }
4472
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004473 int syncFd = -1;
4474 // create an EGLImage from the buffer so we can later
4475 // turn it into a texture
4476 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4477 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4478 if (image == EGL_NO_IMAGE_KHR) {
4479 return BAD_VALUE;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004480 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004481
Dan Stozaabcda352017-06-01 14:37:39 -07004482 // This will automatically destroy the image if we return before calling its destroy method
4483 ImageHolder imageHolder(mEGLDisplay, image);
4484
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004485 // this binds the given EGLImage as a framebuffer for the
4486 // duration of this scope.
4487 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
Dan Stozaabcda352017-06-01 14:37:39 -07004488 if (imageBond.getStatus() != NO_ERROR) {
4489 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004490 return INVALID_OPERATION;
4491 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004492
Dan Stozaabcda352017-06-01 14:37:39 -07004493 // this will in fact render into our dequeued buffer
4494 // via an FBO, which means we didn't have to create
4495 // an EGLSurface and therefore we're not
4496 // dependent on the context's EGLConfig.
4497 renderScreenImplLocked(
4498 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4499 useIdentityTransform, rotation);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004500
Dan Stozaabcda352017-06-01 14:37:39 -07004501 // Attempt to create a sync khr object that can produce a sync point. If that
4502 // isn't available, create a non-dupable sync object in the fallback path and
4503 // wait on it directly.
4504 EGLSyncKHR sync = EGL_NO_SYNC_KHR;
4505 if (!DEBUG_SCREENSHOTS) {
4506 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
4507 // native fence fd will not be populated until flush() is done.
4508 getRenderEngine().flush();
4509 }
4510
4511 if (sync != EGL_NO_SYNC_KHR) {
4512 // get the sync fd
4513 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4514 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4515 ALOGW("captureScreen: failed to dup sync khr object");
4516 syncFd = -1;
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004517 }
Dan Stozaabcda352017-06-01 14:37:39 -07004518 eglDestroySyncKHR(mEGLDisplay, sync);
4519 } else {
4520 // fallback path
4521 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004522 if (sync != EGL_NO_SYNC_KHR) {
Dan Stozaabcda352017-06-01 14:37:39 -07004523 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4524 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4525 EGLint eglErr = eglGetError();
4526 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4527 ALOGW("captureScreen: fence wait timed out");
4528 } else {
4529 ALOGW_IF(eglErr != EGL_SUCCESS,
4530 "captureScreen: error waiting on EGL fence: %#x", eglErr);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004531 }
4532 eglDestroySyncKHR(mEGLDisplay, sync);
4533 } else {
Dan Stozaabcda352017-06-01 14:37:39 -07004534 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004535 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004536 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004537 *outSyncFd = syncFd;
Dan Stozaabcda352017-06-01 14:37:39 -07004538
4539 if (DEBUG_SCREENSHOTS) {
4540 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4541 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4542 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4543 hw, minLayerZ, maxLayerZ);
4544 delete [] pixels;
4545 }
4546
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004547 // destroy our image
Dan Stozaabcda352017-06-01 14:37:39 -07004548 imageHolder.destroy();
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004549
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004550 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004551}
4552
Mathias Agopiand5556842013-09-19 17:08:37 -07004553void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004554 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004555 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004556 for (size_t y=0 ; y<h ; y++) {
4557 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4558 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004559 if (p[x] != 0xFF000000) return;
4560 }
4561 }
4562 ALOGE("*** we just took a black screenshot ***\n"
4563 "requested minz=%d, maxz=%d, layerStack=%d",
4564 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004565
Robert Carr2047fae2016-11-28 14:09:09 -08004566 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004567 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004568 const Layer::State& state(layer->getDrawingState());
Chia-I Wuab0c3192017-08-01 11:29:00 -07004569 if (layer->belongsToDisplay(hw->getLayerStack(), false) && state.z >= minLayerZ &&
Robert Carr1f0a16a2016-10-24 16:27:39 -07004570 state.z <= maxLayerZ) {
Dan Stoza412903f2017-04-27 13:42:17 -07004571 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004572 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4573 layer->isVisible() ? '+' : '-',
4574 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004575 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004576 i++;
4577 });
4578 }
4579 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004580 }
4581}
4582
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004583// ---------------------------------------------------------------------------
4584
Dan Stoza412903f2017-04-27 13:42:17 -07004585void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4586 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004587}
4588
Dan Stoza412903f2017-04-27 13:42:17 -07004589void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4590 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004591}
4592
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004593}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004594
4595
4596#if defined(__gl_h_)
4597#error "don't include gl/gl.h in this file"
4598#endif
4599
4600#if defined(__gl2_h_)
4601#error "don't include gl2/gl2.h in this file"
4602#endif