blob: c34854b6899fbe4e74a29fe9a3d81b6d83602091 [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"
David Sodman0c69cad2017-08-21 12:12:51 -070075#include "BufferLayer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070076#include "LayerVector.h"
chaviw13fdc492017-06-27 12:40:18 -070077#include "ColorLayer.h"
Robert Carr1db73f62016-12-21 12:58:51 -080078#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080080
Steven Thomasb02664d2017-07-26 18:48:28 -070081#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070082#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070083#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070084#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080085
Mathias Agopianff2ed702013-09-01 21:36:12 -070086#include "Effects/Daltonizer.h"
87
Mathias Agopian875d8e12013-06-07 15:35:48 -070088#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070089#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070090
Jiyong Park4b20c2e2017-01-14 19:45:11 +090091#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090092#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090093
chaviw1d044282017-09-27 12:19:28 -070094#include <layerproto/LayerProtoParser.h>
95
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080096#define DISPLAY_COUNT 1
97
Mathias Agopianfee2b462013-07-03 12:34:01 -070098/*
99 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
100 * black pixels.
101 */
102#define DEBUG_SCREENSHOTS false
103
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800104namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700105
Jaesoo Lee43518572017-01-23 19:03:16 +0900106using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900107using namespace android::hardware::configstore::V1_0;
108
Steven Thomasb02664d2017-07-26 18:48:28 -0700109namespace {
110class ConditionalLock {
111public:
112 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
113 if (lock) {
114 mMutex.lock();
115 }
116 }
117 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
118private:
119 Mutex& mMutex;
120 bool mLocked;
121};
122} // namespace anonymous
123
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800124// ---------------------------------------------------------------------------
125
Mathias Agopian99b49842011-06-27 16:05:52 -0700126const String16 sHardwareTest("android.permission.HARDWARE_TEST");
127const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
128const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
129const String16 sDump("android.permission.DUMP");
130
131// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800132int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
133int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700134bool SurfaceFlinger::useContextPriority;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700135int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700136bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800137uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800138bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800139bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800140int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600141bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700142
Kalle Raitaa099a242017-01-11 11:17:29 -0800143
144std::string getHwcServiceName() {
145 char value[PROPERTY_VALUE_MAX] = {};
146 property_get("debug.sf.hwc_service_name", value, "default");
147 ALOGI("Using HWComposer service: '%s'", value);
148 return std::string(value);
149}
150
151bool useTrebleTestingOverride() {
152 char value[PROPERTY_VALUE_MAX] = {};
153 property_get("debug.sf.treble_testing_override", value, "false");
154 ALOGI("Treble testing override: '%s'", value);
155 return std::string(value) == "true";
156}
157
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800158SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700159 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800160 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700161 mTransactionPending(false),
162 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700163 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700164 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700165 mRepaintEverything(0),
Kalle Raitaa099a242017-01-11 11:17:29 -0800166 mHwcServiceName(getHwcServiceName()),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800167 mRenderEngine(nullptr),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800168 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800169 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800170 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800171 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800172 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800173 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700174 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700175 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700176 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700177 mDebugInSwapBuffers(0),
178 mLastSwapBufferTime(0),
179 mDebugInTransaction(0),
180 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700181 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700182 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800183 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000184 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700185 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700186 mHWVsyncAvailable(false),
Romain Guya9638732017-06-01 12:05:21 -0700187 mHasColorMatrix(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800188 mHasPoweredOff(false),
189 mFrameBuckets(),
190 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700191 mLastSwapTime(0),
Steven Thomas050b2c82017-03-06 11:45:16 -0800192 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700193 mVrFlingerRequestsDisplay(false),
194 mMainThreadId(std::this_thread::get_id()),
195 mComposerSequenceId(0)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800196{
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800197 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800198
199 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
200 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
201
202 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
203 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
204
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800205 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
206 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800207
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700208 useContextPriority = getBool< ISurfaceFlingerConfigs,
209 &ISurfaceFlingerConfigs::useContextPriority>(false);
210
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700211 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
212 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
213
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700214 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
215 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
216
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800217 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
218 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
219
Steven Thomas050b2c82017-03-06 11:45:16 -0800220 // Vr flinger is only enabled on Daydream ready devices.
221 useVrFlinger = getBool< ISurfaceFlingerConfigs,
222 &ISurfaceFlingerConfigs::useVrFlinger>(false);
223
Fabien Sanglard1971b632017-03-10 14:50:03 -0800224 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
225 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
226
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600227 hasWideColorDisplay =
228 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
229
Saurabh Shahf4174532017-07-13 10:45:07 -0700230 mPrimaryDispSync.init(hasSyncFramework, dispSyncPresentTimeOffset);
231
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800232 // debugging stuff...
233 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700234
Mathias Agopianb4b17302013-03-20 18:36:41 -0700235 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700236 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700237
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800238 property_get("debug.sf.showupdates", value, "0");
239 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700240
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700241 property_get("debug.sf.ddms", value, "0");
242 mDebugDDMS = atoi(value);
243 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700244 if (!startDdmConnection()) {
245 // start failed, and DDMS debugging not enabled
246 mDebugDDMS = 0;
247 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700248 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700249 ALOGI_IF(mDebugRegion, "showupdates enabled");
250 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700251
252 property_get("debug.sf.disable_backpressure", value, "0");
253 mPropagateBackpressure = !atoi(value);
254 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700255
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800256 property_get("debug.sf.enable_hwc_vds", value, "0");
257 mUseHwcVirtualDisplays = atoi(value);
258 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800259
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800260 property_get("ro.sf.disable_triple_buffer", value, "1");
261 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800262 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700263
Romain Guy11d63f42017-07-20 12:47:14 -0700264 // We should be reading 'persist.sys.sf.color_saturation' here
265 // but since /data may be encrypted, we need to wait until after vold
266 // comes online to attempt to read the property. The property is
267 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800268
269 if (useTrebleTestingOverride()) {
270 // Without the override SurfaceFlinger cannot connect to HIDL
271 // services that are not listed in the manifests. Considered
272 // deriving the setting from the set service name, but it
273 // would be brittle if the name that's not 'default' is used
274 // for production purposes later on.
275 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
276 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800277}
278
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800279void SurfaceFlinger::onFirstRef()
280{
281 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800282}
283
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800284SurfaceFlinger::~SurfaceFlinger()
285{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800286}
287
Dan Stozac7014012014-02-14 15:03:43 -0800288void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800289{
290 // the window manager died on us. prepare its eulogy.
291
Andy McFadden13a082e2012-08-24 10:16:42 -0700292 // restore initial conditions (default device unblank, etc)
293 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800294
295 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700296 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800297}
298
Robert Carr1db73f62016-12-21 12:58:51 -0800299static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700300 status_t err = client->initCheck();
301 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800302 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800303 }
Robert Carr1db73f62016-12-21 12:58:51 -0800304 return nullptr;
305}
306
307sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
308 return initClient(new Client(this));
309}
310
311sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
312 const sp<IGraphicBufferProducer>& gbp) {
313 if (authenticateSurfaceTexture(gbp) == false) {
314 return nullptr;
315 }
316 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
317 if (layer == nullptr) {
318 return nullptr;
319 }
320
321 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800322}
323
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700324sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
325 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700326{
327 class DisplayToken : public BBinder {
328 sp<SurfaceFlinger> flinger;
329 virtual ~DisplayToken() {
330 // no more references, this display must be terminated
331 Mutex::Autolock _l(flinger->mStateLock);
332 flinger->mCurrentState.displays.removeItem(this);
333 flinger->setTransactionFlags(eDisplayTransactionNeeded);
334 }
335 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700336 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700337 : flinger(flinger) {
338 }
339 };
340
341 sp<BBinder> token = new DisplayToken(this);
342
343 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700344 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700345 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700346 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700347 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700348 return token;
349}
350
Jesse Hall6c913be2013-08-08 12:15:49 -0700351void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
352 Mutex::Autolock _l(mStateLock);
353
354 ssize_t idx = mCurrentState.displays.indexOfKey(display);
355 if (idx < 0) {
356 ALOGW("destroyDisplay: invalid display token");
357 return;
358 }
359
360 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
361 if (!info.isVirtualDisplay()) {
362 ALOGE("destroyDisplay called for non-virtual display");
363 return;
364 }
Irvelffc9efc2016-07-27 15:16:37 -0700365 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700366 mCurrentState.displays.removeItemsAt(idx);
367 setTransactionFlags(eDisplayTransactionNeeded);
368}
369
Jesse Hall692c7232012-11-08 15:41:56 -0800370void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800371 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800372 ALOGW_IF(mBuiltinDisplays[type],
373 "Overwriting display token for display type %d", type);
374 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800375 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700376 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800377 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700378 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800379}
380
Mathias Agopiane57f2922012-08-09 16:29:12 -0700381sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700382 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700383 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
384 return NULL;
385 }
Jesse Hall692c7232012-11-08 15:41:56 -0800386 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700387}
388
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800389void SurfaceFlinger::bootFinished()
390{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700391 if (mStartPropertySetThread->join() != NO_ERROR) {
392 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800393 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800394 const nsecs_t now = systemTime();
395 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000396 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700397
398 // wait patiently for the window manager death
399 const String16 name("window");
400 sp<IBinder> window(defaultServiceManager()->getService(name));
401 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700402 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700403 }
404
Steven Thomas050b2c82017-03-06 11:45:16 -0800405 if (mVrFlinger) {
406 mVrFlinger->OnBootFinished();
407 }
408
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700409 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700410 // formerly we would just kill the process, but we now ask it to exit so it
411 // can choose where to stop the animation.
412 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700413
414 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
415 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
416 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700417
Thierry Strudel2924d012017-08-14 15:19:37 -0700418 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700419 readPersistentProperties();
420 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700421 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800422}
423
Mathias Agopian3f844832013-08-07 21:24:32 -0700424void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700425 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700426 RenderEngine& engine;
427 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700428 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700429 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
430 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700431 }
432 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700433 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700434 return true;
435 }
436 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700437 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700438}
439
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700440class DispSyncSource : public VSyncSource, private DispSync::Callback {
441public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700442 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000443 const char* name) :
444 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700445 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700446 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000447 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
448 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700449 mDispSync(dispSync),
450 mCallbackMutex(),
451 mCallback(),
452 mVsyncMutex(),
453 mPhaseOffset(phaseOffset),
454 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700455
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700456 virtual ~DispSyncSource() {}
457
458 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700459 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700460 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000461 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700462 static_cast<DispSync::Callback*>(this));
463 if (err != NO_ERROR) {
464 ALOGE("error registering vsync callback: %s (%d)",
465 strerror(-err), err);
466 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700467 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700468 } else {
469 status_t err = mDispSync->removeEventListener(
470 static_cast<DispSync::Callback*>(this));
471 if (err != NO_ERROR) {
472 ALOGE("error unregistering vsync callback: %s (%d)",
473 strerror(-err), err);
474 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700475 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700476 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700477 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700478 }
479
480 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700481 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700482 mCallback = callback;
483 }
484
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700485 virtual void setPhaseOffset(nsecs_t phaseOffset) {
486 Mutex::Autolock lock(mVsyncMutex);
487
488 // Normalize phaseOffset to [0, period)
489 auto period = mDispSync->getPeriod();
490 phaseOffset %= period;
491 if (phaseOffset < 0) {
492 // If we're here, then phaseOffset is in (-period, 0). After this
493 // operation, it will be in (0, period)
494 phaseOffset += period;
495 }
496 mPhaseOffset = phaseOffset;
497
498 // If we're not enabled, we don't need to mess with the listeners
499 if (!mEnabled) {
500 return;
501 }
502
503 // Remove the listener with the old offset
504 status_t err = mDispSync->removeEventListener(
505 static_cast<DispSync::Callback*>(this));
506 if (err != NO_ERROR) {
507 ALOGE("error unregistering vsync callback: %s (%d)",
508 strerror(-err), err);
509 }
510
511 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000512 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700513 static_cast<DispSync::Callback*>(this));
514 if (err != NO_ERROR) {
515 ALOGE("error registering vsync callback: %s (%d)",
516 strerror(-err), err);
517 }
518 }
519
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700520private:
521 virtual void onDispSyncEvent(nsecs_t when) {
522 sp<VSyncSource::Callback> callback;
523 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700524 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700525 callback = mCallback;
526
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700527 if (mTraceVsync) {
528 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700529 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700530 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700531 }
532
533 if (callback != NULL) {
534 callback->onVSyncEvent(when);
535 }
536 }
537
Tim Murray4a4e4a22016-04-19 16:29:23 +0000538 const char* const mName;
539
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700540 int mValue;
541
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700542 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700543 const String8 mVsyncOnLabel;
544 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700545
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700546 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700547
548 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700549 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700550
551 Mutex mVsyncMutex; // Protects the following
552 nsecs_t mPhaseOffset;
553 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700554};
555
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700556class InjectVSyncSource : public VSyncSource {
557public:
558 InjectVSyncSource() {}
559
560 virtual ~InjectVSyncSource() {}
561
562 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
563 std::lock_guard<std::mutex> lock(mCallbackMutex);
564 mCallback = callback;
565 }
566
567 virtual void onInjectSyncEvent(nsecs_t when) {
568 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700569 if (mCallback) {
570 mCallback->onVSyncEvent(when);
571 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700572 }
573
574 virtual void setVSyncEnabled(bool) {}
575 virtual void setPhaseOffset(nsecs_t) {}
576
577private:
578 std::mutex mCallbackMutex; // Protects the following
579 sp<VSyncSource::Callback> mCallback;
580};
581
Wei Wangf9b05ee2017-07-19 20:59:39 -0700582// Do not call property_set on main thread which will be blocked by init
583// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700584void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700585 ALOGI( "SurfaceFlinger's main thread ready to run. "
586 "Initializing graphics H/W...");
587
Thierry Strudel2924d012017-08-14 15:19:37 -0700588 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900589
Steven Thomasb02664d2017-07-26 18:48:28 -0700590 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800591
Steven Thomasb02664d2017-07-26 18:48:28 -0700592 // start the EventThread
593 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
594 vsyncPhaseOffsetNs, true, "app");
595 mEventThread = new EventThread(vsyncSrc, *this, false);
596 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
597 sfVsyncPhaseOffsetNs, true, "sf");
598 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
599 mEventQueue.setEventThread(mSFEventThread);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800600
Steven Thomasb02664d2017-07-26 18:48:28 -0700601 // set EventThread and SFEventThread to SCHED_FIFO to minimize jitter
602 struct sched_param param = {0};
603 param.sched_priority = 2;
604 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
605 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
606 }
607 if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
608 ALOGE("Couldn't set SCHED_FIFO for EventThread");
Dan Stoza9e56aa02015-11-02 13:00:03 -0800609 }
610
Steven Thomasb02664d2017-07-26 18:48:28 -0700611 // Get a RenderEngine for the given display / config (can't fail)
Chia-I Wud4d9c6f2017-11-09 16:55:31 -0800612 mRenderEngine = RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
Steven Thomasb02664d2017-07-26 18:48:28 -0700613 hasWideColorDisplay ? RenderEngine::WIDE_COLOR_SUPPORT : 0);
Chia-I Wud4d9c6f2017-11-09 16:55:31 -0800614 LOG_ALWAYS_FATAL_IF(mRenderEngine == nullptr, "couldn't create RenderEngine");
Dan Stoza9e56aa02015-11-02 13:00:03 -0800615
Chia-I Wud4d9c6f2017-11-09 16:55:31 -0800616 // retrieve the EGL display/context that was selected/created
617 mEGLDisplay = mRenderEngine->getEGLDisplay();
Steven Thomasb02664d2017-07-26 18:48:28 -0700618 mEGLContext = mRenderEngine->getEGLContext();
619
Steven Thomasb02664d2017-07-26 18:48:28 -0700620 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
621 "Starting with vr flinger active is not currently supported.");
622 mHwc.reset(new HWComposer(mHwcServiceName));
623 mHwc->registerCallback(this, mComposerSequenceId);
Jesse Hall692c7232012-11-08 15:41:56 -0800624
Steven Thomas050b2c82017-03-06 11:45:16 -0800625 if (useVrFlinger) {
626 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700627 // This callback is called from the vr flinger dispatch thread. We
628 // need to call signalTransaction(), which requires holding
629 // mStateLock when we're not on the main thread. Acquiring
630 // mStateLock from the vr flinger dispatch thread might trigger a
631 // deadlock in surface flinger (see b/66916578), so post a message
632 // to be handled on the main thread instead.
633 sp<LambdaMessage> message = new LambdaMessage([=]() {
634 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
635 mVrFlingerRequestsDisplay = requestDisplay;
636 signalTransaction();
637 });
638 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800639 };
640 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800641 mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
642 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800643 if (!mVrFlinger) {
644 ALOGE("Failed to start vrflinger");
645 }
646 }
647
Jamie Gennisd1700752013-10-14 12:22:52 -0700648 mEventControlThread = new EventControlThread(this);
649 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
650
Mathias Agopian92a979a2012-08-02 18:32:23 -0700651 // initialize our drawing state
652 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700653
Andy McFadden13a082e2012-08-24 10:16:42 -0700654 // set initial conditions (e.g. unblank default device)
655 initializeDisplays();
656
Dan Stoza4e637772016-07-28 13:31:51 -0700657 mRenderEngine->primeCache();
658
Wei Wangf9b05ee2017-07-19 20:59:39 -0700659 // Inform native graphics APIs whether the present timestamp is supported:
660 if (getHwComposer().hasCapability(
661 HWC2::Capability::PresentFenceIsNotReliable)) {
662 mStartPropertySetThread = new StartPropertySetThread(false);
663 } else {
664 mStartPropertySetThread = new StartPropertySetThread(true);
665 }
666
667 if (mStartPropertySetThread->Start() != NO_ERROR) {
668 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800669 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800670
Dan Stoza9e56aa02015-11-02 13:00:03 -0800671 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700672}
673
Romain Guy11d63f42017-07-20 12:47:14 -0700674void SurfaceFlinger::readPersistentProperties() {
675 char value[PROPERTY_VALUE_MAX];
676
677 property_get("persist.sys.sf.color_saturation", value, "1.0");
678 mSaturation = atof(value);
679 ALOGV("Saturation is set to %.2f", mSaturation);
Romain Guy54f154a2017-10-24 21:40:32 +0100680
681 property_get("persist.sys.sf.native_mode", value, "0");
682 mForceNativeColorMode = atoi(value) == 1;
683 if (mForceNativeColorMode) {
684 ALOGV("Forcing native color mode");
685 }
Romain Guy11d63f42017-07-20 12:47:14 -0700686}
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 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700732 ConditionalLock _l(mStateLock,
733 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700734 if (!getHwComposer().hasCapability(
735 HWC2::Capability::PresentFenceIsNotReliable)) {
736 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
737 }
738 return NO_ERROR;
739}
740
Dan Stoza7f7da322014-05-02 15:26:25 -0700741status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
742 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700743 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700744 return BAD_VALUE;
745 }
746
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500747 if (!display.get())
748 return NAME_NOT_FOUND;
749
Jesse Hall692c7232012-11-08 15:41:56 -0800750 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700751 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800752 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700753 type = i;
754 break;
755 }
756 }
757
758 if (type < 0) {
759 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700760 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700761
Mathias Agopian8b736f12012-08-13 17:54:26 -0700762 // TODO: Not sure if display density should handled by SF any longer
763 class Density {
764 static int getDensityFromProperty(char const* propName) {
765 char property[PROPERTY_VALUE_MAX];
766 int density = 0;
767 if (property_get(propName, property, NULL) > 0) {
768 density = atoi(property);
769 }
770 return density;
771 }
772 public:
773 static int getEmuDensity() {
774 return getDensityFromProperty("qemu.sf.lcd_density"); }
775 static int getBuildDensity() {
776 return getDensityFromProperty("ro.sf.lcd_density"); }
777 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700778
Dan Stoza7f7da322014-05-02 15:26:25 -0700779 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700780
Steven Thomas6d8110b2017-08-31 18:24:21 -0700781 ConditionalLock _l(mStateLock,
782 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800783 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700784 DisplayInfo info = DisplayInfo();
785
Dan Stoza9e56aa02015-11-02 13:00:03 -0800786 float xdpi = hwConfig->getDpiX();
787 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700788
789 if (type == DisplayDevice::DISPLAY_PRIMARY) {
790 // The density of the device is provided by a build property
791 float density = Density::getBuildDensity() / 160.0f;
792 if (density == 0) {
793 // the build doesn't provide a density -- this is wrong!
794 // use xdpi instead
795 ALOGE("ro.sf.lcd_density must be defined as a build property");
796 density = xdpi / 160.0f;
797 }
798 if (Density::getEmuDensity()) {
799 // if "qemu.sf.lcd_density" is specified, it overrides everything
800 xdpi = ydpi = density = Density::getEmuDensity();
801 density /= 160.0f;
802 }
803 info.density = density;
804
805 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700806 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000807 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700808 } else {
809 // TODO: where should this value come from?
810 static const int TV_DENSITY = 213;
811 info.density = TV_DENSITY / 160.0f;
812 info.orientation = 0;
813 }
814
Dan Stoza9e56aa02015-11-02 13:00:03 -0800815 info.w = hwConfig->getWidth();
816 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700817 info.xdpi = xdpi;
818 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800819 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900820 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800821
Andy McFadden91b2ca82014-06-13 14:04:23 -0700822 // This is how far in advance a buffer must be queued for
823 // presentation at a given time. If you want a buffer to appear
824 // on the screen at time N, you must submit the buffer before
825 // (N - presentationDeadline).
826 //
827 // Normally it's one full refresh period (to give SF a chance to
828 // latch the buffer), but this can be reduced by configuring a
829 // DispSync offset. Any additional delays introduced by the hardware
830 // composer or panel must be accounted for here.
831 //
832 // We add an additional 1ms to allow for processing time and
833 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800834 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800835 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700836
837 // All non-virtual displays are currently considered secure.
838 info.secure = true;
839
Michael Wright28f24d02016-07-12 13:30:53 -0700840 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700841 }
842
Dan Stoza7f7da322014-05-02 15:26:25 -0700843 return NO_ERROR;
844}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700845
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800846status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700847 DisplayStatInfo* stats) {
848 if (stats == NULL) {
849 return BAD_VALUE;
850 }
851
852 // FIXME for now we always return stats for the primary display
853 memset(stats, 0, sizeof(*stats));
854 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
855 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
856 return NO_ERROR;
857}
858
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700859int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800860 if (display == NULL) {
861 ALOGE("%s : display is NULL", __func__);
862 return BAD_VALUE;
863 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700864
865 sp<const DisplayDevice> device(getDisplayDevice(display));
Dan Stoza24a42e92015-03-09 10:04:11 -0700866 if (device != NULL) {
867 return device->getActiveConfig();
868 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700869
Dan Stoza24a42e92015-03-09 10:04:11 -0700870 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700871}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700872
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700873void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
874 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
875 this);
876 int32_t type = hw->getDisplayType();
877 int currentMode = hw->getActiveConfig();
878
879 if (mode == currentMode) {
880 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
881 return;
882 }
883
884 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
885 ALOGW("Trying to set config for virtual display");
886 return;
887 }
888
889 hw->setActiveConfig(mode);
890 getHwComposer().setActiveConfig(type, mode);
891}
892
893status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
894 class MessageSetActiveConfig: public MessageBase {
895 SurfaceFlinger& mFlinger;
896 sp<IBinder> mDisplay;
897 int mMode;
898 public:
899 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
900 int mode) :
901 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
902 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700903 Vector<DisplayInfo> configs;
904 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700905 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700906 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700907 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700908 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700909 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700910 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
911 if (hw == NULL) {
912 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700913 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700914 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
915 ALOGW("Attempt to set active config = %d for virtual display",
916 mMode);
917 } else {
918 mFlinger.setActiveConfigInternal(hw, mMode);
919 }
920 return true;
921 }
922 };
923 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
924 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700925 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700926}
Michael Wright28f24d02016-07-12 13:30:53 -0700927status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
928 Vector<android_color_mode_t>* outColorModes) {
929 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
930 return BAD_VALUE;
931 }
932
933 if (!display.get()) {
934 return NAME_NOT_FOUND;
935 }
936
937 int32_t type = NAME_NOT_FOUND;
938 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
939 if (display == mBuiltinDisplays[i]) {
940 type = i;
941 break;
942 }
943 }
944
945 if (type < 0) {
946 return type;
947 }
948
Steven Thomas6d8110b2017-08-31 18:24:21 -0700949 std::vector<android_color_mode_t> modes;
950 {
951 ConditionalLock _l(mStateLock,
952 std::this_thread::get_id() != mMainThreadId);
953 modes = getHwComposer().getColorModes(type);
954 }
Michael Wright28f24d02016-07-12 13:30:53 -0700955 outColorModes->clear();
956 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
957
958 return NO_ERROR;
959}
960
961android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700962 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700963 if (device != nullptr) {
964 return device->getActiveColorMode();
965 }
966 return static_cast<android_color_mode_t>(BAD_VALUE);
967}
968
969void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
970 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700971 int32_t type = hw->getDisplayType();
972 android_color_mode_t currentMode = hw->getActiveColorMode();
973
974 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700975 return;
976 }
977
978 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
979 ALOGW("Trying to set config for virtual display");
980 return;
981 }
982
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600983 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
984 hw->getDisplayType());
985
Michael Wright28f24d02016-07-12 13:30:53 -0700986 hw->setActiveColorMode(mode);
987 getHwComposer().setActiveColorMode(type, mode);
988}
989
990
991status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
992 android_color_mode_t colorMode) {
993 class MessageSetActiveColorMode: public MessageBase {
994 SurfaceFlinger& mFlinger;
995 sp<IBinder> mDisplay;
996 android_color_mode_t mMode;
997 public:
998 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
999 android_color_mode_t mode) :
1000 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1001 virtual bool handler() {
1002 Vector<android_color_mode_t> modes;
1003 mFlinger.getDisplayColorModes(mDisplay, &modes);
1004 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
1005 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001006 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1007 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001008 return true;
1009 }
1010 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1011 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001012 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1013 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001014 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001015 ALOGW("Attempt to set active color mode %s %d for virtual display",
1016 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001017 } else {
1018 mFlinger.setActiveColorModeInternal(hw, mMode);
1019 }
1020 return true;
1021 }
1022 };
1023 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1024 postMessageSync(msg);
1025 return NO_ERROR;
1026}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001027
Svetoslavd85084b2014-03-20 10:28:31 -07001028status_t SurfaceFlinger::clearAnimationFrameStats() {
1029 Mutex::Autolock _l(mStateLock);
1030 mAnimFrameTracker.clearStats();
1031 return NO_ERROR;
1032}
1033
1034status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1035 Mutex::Autolock _l(mStateLock);
1036 mAnimFrameTracker.getStats(outStats);
1037 return NO_ERROR;
1038}
1039
Dan Stozac4f471e2016-03-24 09:31:08 -07001040status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1041 HdrCapabilities* outCapabilities) const {
1042 Mutex::Autolock _l(mStateLock);
1043
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001044 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001045 if (displayDevice == nullptr) {
1046 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1047 return BAD_VALUE;
1048 }
1049
1050 std::unique_ptr<HdrCapabilities> capabilities =
1051 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
1052 if (capabilities) {
1053 std::swap(*outCapabilities, *capabilities);
1054 } else {
1055 return BAD_VALUE;
1056 }
1057
1058 return NO_ERROR;
1059}
1060
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001061status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001062 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1063 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001064
Chia-I Wu90f669f2017-10-05 14:24:41 -07001065 if (mInjectVSyncs == enable) {
1066 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001067 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001068
1069 if (enable) {
1070 ALOGV("VSync Injections enabled");
1071 if (mVSyncInjector.get() == nullptr) {
1072 mVSyncInjector = new InjectVSyncSource();
1073 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
1074 }
1075 mEventQueue.setEventThread(mInjectorEventThread);
1076 } else {
1077 ALOGV("VSync Injections disabled");
1078 mEventQueue.setEventThread(mSFEventThread);
1079 }
1080
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001081 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001082 });
1083 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001084 return NO_ERROR;
1085}
1086
1087status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001088 Mutex::Autolock _l(mStateLock);
1089
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001090 if (!mInjectVSyncs) {
1091 ALOGE("VSync Injections not enabled");
1092 return BAD_VALUE;
1093 }
1094 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1095 ALOGV("Injecting VSync inside SurfaceFlinger");
1096 mVSyncInjector->onInjectSyncEvent(when);
1097 }
1098 return NO_ERROR;
1099}
1100
Kalle Raitaa099a242017-01-11 11:17:29 -08001101status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const {
1102 IPCThreadState* ipc = IPCThreadState::self();
1103 const int pid = ipc->getCallingPid();
1104 const int uid = ipc->getCallingUid();
1105 if ((uid != AID_SHELL) &&
1106 !PermissionCache::checkPermission(sDump, pid, uid)) {
1107 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1108 return PERMISSION_DENIED;
1109 }
1110
1111 // Try to acquire a lock for 1s, fail gracefully
1112 const status_t err = mStateLock.timedLock(s2ns(1));
1113 const bool locked = (err == NO_ERROR);
1114 if (!locked) {
1115 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1116 return TIMED_OUT;
1117 }
1118
1119 outLayers->clear();
1120 mCurrentState.traverseInZOrder([&](Layer* layer) {
1121 outLayers->push_back(layer->getLayerDebugInfo());
1122 });
1123
1124 mStateLock.unlock();
1125 return NO_ERROR;
1126}
1127
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001128// ----------------------------------------------------------------------------
1129
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001130sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1131 ISurfaceComposer::VsyncSource vsyncSource) {
1132 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1133 return mSFEventThread->createEventConnection();
1134 } else {
1135 return mEventThread->createEventConnection();
1136 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001137}
1138
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001139// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001140
1141void SurfaceFlinger::waitForEvent() {
1142 mEventQueue.waitMessage();
1143}
1144
1145void SurfaceFlinger::signalTransaction() {
1146 mEventQueue.invalidate();
1147}
1148
1149void SurfaceFlinger::signalLayerUpdate() {
1150 mEventQueue.invalidate();
1151}
1152
1153void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001154 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001155 mEventQueue.refresh();
1156}
1157
1158status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001159 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001160 return mEventQueue.postMessage(msg, reltime);
1161}
1162
1163status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001164 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001165 status_t res = mEventQueue.postMessage(msg, reltime);
1166 if (res == NO_ERROR) {
1167 msg->wait();
1168 }
1169 return res;
1170}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001171
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001172void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001173 do {
1174 waitForEvent();
1175 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001176}
1177
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001178void SurfaceFlinger::enableHardwareVsync() {
1179 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001180 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001181 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001182 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1183 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001184 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001185 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001186}
1187
Jesse Hall948fe0c2013-10-14 12:56:09 -07001188void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001189 Mutex::Autolock _l(mHWVsyncLock);
1190
Jesse Hall948fe0c2013-10-14 12:56:09 -07001191 if (makeAvailable) {
1192 mHWVsyncAvailable = true;
1193 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001194 // Hardware vsync is not currently available, so abort the resync
1195 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001196 return;
1197 }
1198
Dan Stoza9e56aa02015-11-02 13:00:03 -08001199 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1200 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001201
1202 mPrimaryDispSync.reset();
1203 mPrimaryDispSync.setPeriod(period);
1204
1205 if (!mPrimaryHWVsyncEnabled) {
1206 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001207 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1208 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001209 mPrimaryHWVsyncEnabled = true;
1210 }
1211}
1212
Jesse Hall948fe0c2013-10-14 12:56:09 -07001213void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001214 Mutex::Autolock _l(mHWVsyncLock);
1215 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001216 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1217 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001218 mPrimaryDispSync.endResync();
1219 mPrimaryHWVsyncEnabled = false;
1220 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001221 if (makeUnavailable) {
1222 mHWVsyncAvailable = false;
1223 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001224}
1225
Tim Murray4a4e4a22016-04-19 16:29:23 +00001226void SurfaceFlinger::resyncWithRateLimit() {
1227 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001228
1229 // No explicit locking is needed here since EventThread holds a lock while calling this method
1230 static nsecs_t sLastResyncAttempted = 0;
1231 const nsecs_t now = systemTime();
1232 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001233 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001234 }
Dan Stoza57164302017-05-08 14:03:54 -07001235 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001236}
1237
Steven Thomasb02664d2017-07-26 18:48:28 -07001238void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1239 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001240 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001241 // Ignore any vsyncs from a previous hardware composer.
1242 if (sequenceId != mComposerSequenceId) {
1243 return;
1244 }
1245
1246 int32_t type;
1247 if (!mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001248 return;
1249 }
1250
Jamie Gennisd1700752013-10-14 12:22:52 -07001251 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001252
Jamie Gennisd1700752013-10-14 12:22:52 -07001253 { // Scope for the lock
1254 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001255 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001256 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001257 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001258 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001259
1260 if (needsHwVsync) {
1261 enableHardwareVsync();
1262 } else {
1263 disableHardwareVsync(false);
1264 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001265}
1266
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001267void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001268 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001269 *compositorTiming = mCompositorTiming;
1270}
1271
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001272void SurfaceFlinger::createDefaultDisplayDevice() {
Steven Thomasb02664d2017-07-26 18:48:28 -07001273 const DisplayDevice::DisplayType type = DisplayDevice::DISPLAY_PRIMARY;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001274 wp<IBinder> token = mBuiltinDisplays[type];
1275
1276 // All non-virtual displays are currently considered secure.
1277 const bool isSecure = true;
1278
1279 sp<IGraphicBufferProducer> producer;
1280 sp<IGraphicBufferConsumer> consumer;
1281 BufferQueue::createBufferQueue(&producer, &consumer);
1282
1283 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1284
1285 bool hasWideColorModes = false;
1286 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1287 for (android_color_mode_t colorMode : modes) {
1288 switch (colorMode) {
1289 case HAL_COLOR_MODE_DISPLAY_P3:
1290 case HAL_COLOR_MODE_ADOBE_RGB:
1291 case HAL_COLOR_MODE_DCI_P3:
1292 hasWideColorModes = true;
1293 break;
1294 default:
1295 break;
1296 }
1297 }
Romain Guy54f154a2017-10-24 21:40:32 +01001298 bool useWideColorMode = hasWideColorModes && hasWideColorDisplay && !mForceNativeColorMode;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001299 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
1300 token, fbs, producer, mRenderEngine->getEGLConfig(),
Romain Guy54f154a2017-10-24 21:40:32 +01001301 useWideColorMode);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001302 mDisplays.add(token, hw);
Thierry Strudel2924d012017-08-14 15:19:37 -07001303 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
Romain Guy54f154a2017-10-24 21:40:32 +01001304 if (useWideColorMode) {
Thierry Strudel2924d012017-08-14 15:19:37 -07001305 defaultColorMode = HAL_COLOR_MODE_SRGB;
1306 }
1307 setActiveColorModeInternal(hw, defaultColorMode);
Courtney Goeltzenleuchter79d27242017-07-13 17:54:01 -06001308 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Steven Thomasb02664d2017-07-26 18:48:28 -07001309
1310 // Add the primary display token to mDrawingState so we don't try to
1311 // recreate the DisplayDevice for the primary display.
1312 mDrawingState.displays.add(token, DisplayDeviceState(type, true));
1313
1314 // make the GLContext current so that we can create textures when creating
1315 // Layers (which may happens before we render something)
Chia-I Wu7f402902017-11-09 12:51:10 -08001316 hw->makeCurrent();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001317}
1318
Steven Thomasb02664d2017-07-26 18:48:28 -07001319void SurfaceFlinger::onHotplugReceived(int32_t sequenceId,
1320 hwc2_display_t display, HWC2::Connection connection,
1321 bool primaryDisplay) {
1322 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s, %s)",
1323 sequenceId, display,
1324 connection == HWC2::Connection::Connected ?
1325 "connected" : "disconnected",
1326 primaryDisplay ? "primary" : "external");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001327
Steven Thomasb02664d2017-07-26 18:48:28 -07001328 // Only lock if we're not on the main thread. This function is normally
1329 // called on a hwbinder thread, but for the primary display it's called on
1330 // the main thread with the state lock already held, so don't attempt to
1331 // acquire it here.
1332 ConditionalLock lock(mStateLock,
1333 std::this_thread::get_id() != mMainThreadId);
1334
1335 if (primaryDisplay) {
1336 mHwc->onHotplug(display, connection);
1337 if (!mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY].get()) {
1338 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001339 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001340 createDefaultDisplayDevice();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001341 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07001342 if (sequenceId != mComposerSequenceId) {
1343 return;
1344 }
1345 if (mHwc->isUsingVrComposer()) {
1346 ALOGE("External displays are not supported by the vr hardware composer.");
1347 return;
1348 }
1349 mHwc->onHotplug(display, connection);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001350 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Steven Thomasb02664d2017-07-26 18:48:28 -07001351 if (connection == HWC2::Connection::Connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001352 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001353 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001354 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1355 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001356 }
1357 setTransactionFlags(eDisplayTransactionNeeded);
1358
Andy McFadden9e9689c2012-10-10 18:17:51 -07001359 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001360 }
Mathias Agopian86303202012-07-24 22:46:10 -07001361}
1362
Steven Thomasb02664d2017-07-26 18:48:28 -07001363void SurfaceFlinger::onRefreshReceived(int sequenceId,
1364 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001365 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001366 if (sequenceId != mComposerSequenceId) {
1367 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001368 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001369 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001370}
1371
Dan Stoza9e56aa02015-11-02 13:00:03 -08001372void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001373 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001374 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001375 getHwComposer().setVsyncEnabled(disp,
1376 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001377}
1378
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001379// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001380void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001381 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001382 // Clear the drawing state so that the logic inside of
1383 // handleTransactionLocked will fire. It will determine the delta between
1384 // mCurrentState and mDrawingState and re-apply all changes when we make the
1385 // transition.
1386 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001387 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001388 mDisplays.clear();
1389}
1390
Steven Thomas050b2c82017-03-06 11:45:16 -08001391void SurfaceFlinger::updateVrFlinger() {
1392 if (!mVrFlinger)
1393 return;
1394 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1395 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001396 return;
1397 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001398
Steven Thomasb02664d2017-07-26 18:48:28 -07001399 if (vrFlingerRequestsDisplay && !mHwc->getComposer()->isRemote()) {
1400 ALOGE("Vr flinger is only supported for remote hardware composer"
1401 " service connections. Ignoring request to transition to vr"
1402 " flinger.");
1403 mVrFlingerRequestsDisplay = false;
1404 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001405 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001406
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001407 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001408
Steven Thomasb02664d2017-07-26 18:48:28 -07001409 int currentDisplayPowerMode = getDisplayDeviceLocked(
1410 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001411
Steven Thomasb02664d2017-07-26 18:48:28 -07001412 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001413 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001414 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001415
Steven Thomasb02664d2017-07-26 18:48:28 -07001416 resetDisplayState();
1417 mHwc.reset(); // Delete the current instance before creating the new one
1418 mHwc.reset(new HWComposer(
1419 vrFlingerRequestsDisplay ? "vr" : mHwcServiceName));
1420 mHwc->registerCallback(this, ++mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001421
Steven Thomasb02664d2017-07-26 18:48:28 -07001422 LOG_ALWAYS_FATAL_IF(!mHwc->getComposer()->isRemote(),
1423 "Switched to non-remote hardware composer");
1424
1425 if (vrFlingerRequestsDisplay) {
1426 mVrFlinger->GrantDisplayOwnership();
1427 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001428 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001429 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001430
1431 mVisibleRegionsDirty = true;
1432 invalidateHwcGeometry();
1433
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001434 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001435 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1436 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1437 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001438
Steven Thomasb02664d2017-07-26 18:48:28 -07001439 // Reset the timing values to account for the period of the swapped in HWC
1440 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1441 const nsecs_t period = activeConfig->getVsyncPeriod();
1442 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001443
Steven Thomasb02664d2017-07-26 18:48:28 -07001444 // Use phase of 0 since phase is not known.
1445 // Use latency of 0, which will snap to the ideal latency.
1446 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001447
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001448 android_atomic_or(1, &mRepaintEverything);
1449 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001450}
1451
Mathias Agopian4fec8732012-06-29 14:12:52 -07001452void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001453 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001454 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001455 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001456 bool frameMissed = !mHadClientComposition &&
1457 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001458 (mPreviousPresentFence->getSignalTime() ==
1459 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001460 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001461 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001462 signalLayerUpdate();
1463 break;
1464 }
1465
Steven Thomas050b2c82017-03-06 11:45:16 -08001466 // Now that we're going to make it to the handleMessageTransaction()
1467 // call below it's safe to call updateVrFlinger(), which will
1468 // potentially trigger a display handoff.
1469 updateVrFlinger();
1470
Dan Stoza6b9454d2014-11-07 16:00:59 -08001471 bool refreshNeeded = handleMessageTransaction();
1472 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001473 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001474 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001475 // Signal a refresh if a transaction modified the window state,
1476 // a new buffer was latched, or if HWC has requested a full
1477 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001478 signalRefresh();
1479 }
1480 break;
1481 }
1482 case MessageQueue::REFRESH: {
1483 handleMessageRefresh();
1484 break;
1485 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001486 }
1487}
1488
Dan Stoza6b9454d2014-11-07 16:00:59 -08001489bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001490 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001491 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001492 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001493 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001494 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001495 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001496}
1497
Dan Stoza6b9454d2014-11-07 16:00:59 -08001498bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001499 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001500 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001501}
1502
1503void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001504 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001505
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001506 mRefreshPending = false;
1507
Pablo Ceballos40845df2016-01-25 17:41:15 -08001508 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001509
Brian Andersond6927fb2016-07-23 23:37:30 -07001510 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001511 rebuildLayerStacks();
1512 setUpHWComposer();
1513 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001514 doTracing("handleRefresh");
Dan Stoza05dacfb2016-07-01 13:33:38 -07001515 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001516 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001517
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001518 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001519
1520 mHadClientComposition = false;
1521 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1522 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1523 mHadClientComposition = mHadClientComposition ||
1524 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1525 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001526
Dan Stoza9e56aa02015-11-02 13:00:03 -08001527 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001528}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001529
Mathias Agopiancd60f992012-08-16 16:28:27 -07001530void SurfaceFlinger::doDebugFlashRegions()
1531{
1532 // is debugging enabled
1533 if (CC_LIKELY(!mDebugRegion))
1534 return;
1535
1536 const bool repaintEverything = mRepaintEverything;
1537 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1538 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001539 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001540 // transform the dirty region into this screen's coordinate space
1541 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1542 if (!dirtyRegion.isEmpty()) {
1543 // redraw the whole screen
1544 doComposeSurfaces(hw, Region(hw->bounds()));
1545
1546 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001547 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001548 RenderEngine& engine(getRenderEngine());
1549 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1550
Mathias Agopianda27af92012-09-13 18:17:13 -07001551 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001552 }
1553 }
1554 }
1555
1556 postFramebuffer();
1557
1558 if (mDebugRegion > 1) {
1559 usleep(mDebugRegion * 1000);
1560 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001561
Dan Stoza9e56aa02015-11-02 13:00:03 -08001562 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001563 auto& displayDevice = mDisplays[displayId];
1564 if (!displayDevice->isDisplayOn()) {
1565 continue;
1566 }
1567
1568 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001569 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1570 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001571 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001572}
1573
Adrian Roos1e1a1282017-11-01 19:05:31 +01001574void SurfaceFlinger::doTracing(const char* where) {
1575 ATRACE_CALL();
1576 ATRACE_NAME(where);
1577 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001578 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001579 }
1580}
1581
Brian Andersond6927fb2016-07-23 23:37:30 -07001582void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001583{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001584 ATRACE_CALL();
1585 ALOGV("preComposition");
1586
Mathias Agopiancd60f992012-08-16 16:28:27 -07001587 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001588 mDrawingState.traverseInZOrder([&](Layer* layer) {
1589 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001590 needExtraInvalidate = true;
1591 }
Robert Carr2047fae2016-11-28 14:09:09 -08001592 });
1593
Mathias Agopiancd60f992012-08-16 16:28:27 -07001594 if (needExtraInvalidate) {
1595 signalLayerUpdate();
1596 }
1597}
1598
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001599void SurfaceFlinger::updateCompositorTiming(
1600 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1601 std::shared_ptr<FenceTime>& presentFenceTime) {
1602 // Update queue of past composite+present times and determine the
1603 // most recently known composite to present latency.
1604 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1605 nsecs_t compositeToPresentLatency = -1;
1606 while (!mCompositePresentTimes.empty()) {
1607 CompositePresentTime& cpt = mCompositePresentTimes.front();
1608 // Cached values should have been updated before calling this method,
1609 // which helps avoid duplicate syscalls.
1610 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1611 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1612 break;
1613 }
1614 compositeToPresentLatency = displayTime - cpt.composite;
1615 mCompositePresentTimes.pop();
1616 }
1617
1618 // Don't let mCompositePresentTimes grow unbounded, just in case.
1619 while (mCompositePresentTimes.size() > 16) {
1620 mCompositePresentTimes.pop();
1621 }
1622
Brian Andersond0010582017-03-07 13:20:31 -08001623 setCompositorTimingSnapped(
1624 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1625}
1626
1627void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1628 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001629 // Integer division and modulo round toward 0 not -inf, so we need to
1630 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001631 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001632 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1633 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1634
Brian Andersond0010582017-03-07 13:20:31 -08001635 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1636 if (idealLatency <= 0) {
1637 idealLatency = vsyncInterval;
1638 }
1639
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001640 // Snap the latency to a value that removes scheduling jitter from the
1641 // composition and present times, which often have >1ms of jitter.
1642 // Reducing jitter is important if an app attempts to extrapolate
1643 // something (such as user input) to an accurate diasplay time.
1644 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1645 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001646 nsecs_t bias = vsyncInterval / 2;
1647 int64_t extraVsyncs =
1648 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1649 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1650 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001651
Brian Andersond0010582017-03-07 13:20:31 -08001652 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001653 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1654 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001655 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001656}
1657
1658void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001659{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001660 ATRACE_CALL();
1661 ALOGV("postComposition");
1662
Brian Anderson3546a3f2016-07-14 11:51:14 -07001663 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001664 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001665 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001666 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001667 }
1668
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001669 // |mStateLock| not needed as we are on the main thread
1670 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001671
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001672 mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001673 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1674 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1675 glCompositionDoneFenceTime =
1676 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1677 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1678 } else {
1679 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1680 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001681
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001682 mDisplayTimeline.updateSignalTimes();
Brian Anderson4e606e32017-03-16 15:34:57 -07001683 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1684 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1685 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001686
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001687 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1688 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1689
1690 // We use the refreshStartTime which might be sampled a little later than
1691 // when we started doing work for this frame, but that should be okay
1692 // since updateCompositorTiming has snapping logic.
1693 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001694 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001695 CompositorTiming compositorTiming;
1696 {
1697 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1698 compositorTiming = mCompositorTiming;
1699 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001700
Robert Carr2047fae2016-11-28 14:09:09 -08001701 mDrawingState.traverseInZOrder([&](Layer* layer) {
1702 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001703 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001704 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001705 recordBufferingStats(layer->getName().string(),
1706 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001707 }
Robert Carr2047fae2016-11-28 14:09:09 -08001708 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001709
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001710 if (presentFenceTime->isValid()) {
1711 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001712 enableHardwareVsync();
1713 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001714 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001715 }
1716 }
1717
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001718 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001719 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001720 enableHardwareVsync();
1721 }
1722 }
1723
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001724 if (mAnimCompositionPending) {
1725 mAnimCompositionPending = false;
1726
Brian Anderson4e606e32017-03-16 15:34:57 -07001727 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001728 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001729 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001730 } else {
1731 // The HWC doesn't support present fences, so use the refresh
1732 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001733 nsecs_t presentTime =
1734 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001735 mAnimFrameTracker.setActualPresentTime(presentTime);
1736 }
1737 mAnimFrameTracker.advanceFrame();
1738 }
Dan Stozab90cf072015-03-05 11:05:59 -08001739
1740 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1741 return;
1742 }
1743
1744 nsecs_t currentTime = systemTime();
1745 if (mHasPoweredOff) {
1746 mHasPoweredOff = false;
1747 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001748 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001749 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001750 if (numPeriods < NUM_BUCKETS - 1) {
1751 mFrameBuckets[numPeriods] += elapsedTime;
1752 } else {
1753 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1754 }
1755 mTotalTime += elapsedTime;
1756 }
1757 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001758}
1759
1760void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001761 ATRACE_CALL();
1762 ALOGV("rebuildLayerStacks");
1763
Mathias Agopiancd60f992012-08-16 16:28:27 -07001764 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001765 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001766 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001767 mVisibleRegionsDirty = false;
1768 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001769
Jeff Sharkey76488112017-02-27 14:15:18 -07001770 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1771 Region opaqueRegion;
1772 Region dirtyRegion;
1773 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001774 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001775 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1776 const Transform& tr(displayDevice->getTransform());
1777 const Rect bounds(displayDevice->getBounds());
1778 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001779 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001780
Jeff Sharkey76488112017-02-27 14:15:18 -07001781 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001782 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001783 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1784 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001785 Region drawRegion(tr.transform(
1786 layer->visibleNonTransparentRegion));
1787 drawRegion.andSelf(bounds);
1788 if (!drawRegion.isEmpty()) {
1789 layersSortedByZ.add(layer);
1790 } else {
1791 // Clear out the HWC layer if this layer was
1792 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001793 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001794 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001795 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001796 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001797 // WM changes displayDevice->layerStack upon sleep/awake.
1798 // Here we make sure we delete the HWC layers even if
1799 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001800 hwcLayerDestroyed = layer->destroyHwcLayer(
1801 displayDevice->getHwcDisplayId());
1802 }
1803
1804 // If a layer is not going to get a release fence because
1805 // it is invisible, but it is also going to release its
1806 // old buffer, add it to the list of layers needing
1807 // fences.
1808 if (hwcLayerDestroyed) {
1809 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1810 mLayersWithQueuedFrames.cend(), layer);
1811 if (found != mLayersWithQueuedFrames.cend()) {
1812 layersNeedingFences.add(layer);
1813 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001814 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001815 });
1816 }
1817 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001818 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001819 displayDevice->undefinedRegion.set(bounds);
1820 displayDevice->undefinedRegion.subtractSelf(
1821 tr.transform(opaqueRegion));
1822 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001823 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001824 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001825}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001826
Romain Guy0147a172017-06-01 13:53:56 -07001827mat4 SurfaceFlinger::computeSaturationMatrix() const {
1828 if (mSaturation == 1.0f) {
1829 return mat4();
1830 }
1831
1832 // Rec.709 luma coefficients
1833 float3 luminance{0.213f, 0.715f, 0.072f};
1834 luminance *= 1.0f - mSaturation;
1835 return mat4(
1836 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1837 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1838 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1839 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1840 );
1841}
1842
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001843// pickColorMode translates a given dataspace into the best available color mode.
1844// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001845android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Romain Guy54f154a2017-10-24 21:40:32 +01001846 if (mForceNativeColorMode) {
1847 return HAL_COLOR_MODE_NATIVE;
1848 }
1849
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001850 switch (dataSpace) {
1851 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1852 // system expects.
1853 case HAL_DATASPACE_UNKNOWN:
1854 case HAL_DATASPACE_SRGB:
1855 case HAL_DATASPACE_V0_SRGB:
1856 return HAL_COLOR_MODE_SRGB;
1857 break;
1858
1859 case HAL_DATASPACE_DISPLAY_P3:
1860 return HAL_COLOR_MODE_DISPLAY_P3;
1861 break;
1862
1863 default:
1864 // TODO (courtneygo): Do we want to assert an error here?
1865 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1866 dataSpace);
1867 return HAL_COLOR_MODE_SRGB;
1868 break;
1869 }
1870}
1871
Romain Guy0147a172017-06-01 13:53:56 -07001872android_dataspace SurfaceFlinger::bestTargetDataSpace(
1873 android_dataspace a, android_dataspace b) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001874 // Only support sRGB and Display-P3 right now.
1875 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1876 return HAL_DATASPACE_DISPLAY_P3;
1877 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001878 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1879 return HAL_DATASPACE_DISPLAY_P3;
1880 }
1881 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1882 return HAL_DATASPACE_DISPLAY_P3;
1883 }
1884
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001885 return HAL_DATASPACE_V0_SRGB;
1886}
1887
Mathias Agopiancd60f992012-08-16 16:28:27 -07001888void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001889 ATRACE_CALL();
1890 ALOGV("setUpHWComposer");
1891
Jesse Hall028dc8f2013-08-20 16:35:32 -07001892 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001893 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1894 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1895 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1896
1897 // If nothing has changed (!dirty), don't recompose.
1898 // If something changed, but we don't currently have any visible layers,
1899 // and didn't when we last did a composition, then skip it this time.
1900 // The second rule does two things:
1901 // - When all layers are removed from a display, we'll emit one black
1902 // frame, then nothing more until we get new layers.
1903 // - When a display is created with a private layer stack, we won't
1904 // emit any black frames until a layer is added to the layer stack.
1905 bool mustRecompose = dirty && !(empty && wasEmpty);
1906
1907 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1908 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1909 mustRecompose ? "doing" : "skipping",
1910 dirty ? "+" : "-",
1911 empty ? "+" : "-",
1912 wasEmpty ? "+" : "-");
1913
Dan Stoza71433162014-02-04 16:22:36 -08001914 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001915
1916 if (mustRecompose) {
1917 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1918 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001919 }
1920
Dan Stoza9e56aa02015-11-02 13:00:03 -08001921 // build the h/w work list
1922 if (CC_UNLIKELY(mGeometryInvalid)) {
1923 mGeometryInvalid = false;
1924 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1925 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1926 const auto hwcId = displayDevice->getHwcDisplayId();
1927 if (hwcId >= 0) {
1928 const Vector<sp<Layer>>& currentLayers(
1929 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001930 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001931 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001932 if (!layer->hasHwcLayer(hwcId)) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001933 if (!layer->createHwcLayer(mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001934 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001935 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001936 }
1937 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001938
Robert Carrae060832016-11-28 10:51:00 -08001939 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001940 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001941 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001942 }
1943 }
1944 }
1945 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001946 }
Riley Andrews03414a12014-07-01 14:22:59 -07001947
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001948
Romain Guy0147a172017-06-01 13:53:56 -07001949 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001950
Dan Stoza9e56aa02015-11-02 13:00:03 -08001951 // Set the per-frame data
1952 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1953 auto& displayDevice = mDisplays[displayId];
1954 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001955
Dan Stoza9e56aa02015-11-02 13:00:03 -08001956 if (hwcId < 0) {
1957 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001958 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001959 if (colorMatrix != mPreviousColorMatrix) {
1960 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1961 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1962 "display %zd: %d", displayId, result);
1963 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001964 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
chaviwc9232ed2017-11-14 15:31:15 -08001965 if (layer->getForceClientComposition(hwcId)) {
1966 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1967 layer->setCompositionType(hwcId, HWC2::Composition::Client);
1968 continue;
1969 }
1970
Dan Stoza9e56aa02015-11-02 13:00:03 -08001971 layer->setPerFrameData(displayDevice);
1972 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001973
1974 if (hasWideColorDisplay) {
1975 android_color_mode newColorMode;
1976 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1977
1978 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1979 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1980 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1981 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1982 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1983 }
1984 newColorMode = pickColorMode(newDataSpace);
1985
Thierry Strudel2924d012017-08-14 15:19:37 -07001986 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001987 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001988 }
1989
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001990 mPreviousColorMatrix = colorMatrix;
1991
Dan Stoza9e56aa02015-11-02 13:00:03 -08001992 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001993 auto& displayDevice = mDisplays[displayId];
1994 if (!displayDevice->isDisplayOn()) {
1995 continue;
1996 }
1997
1998 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001999 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2000 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002001 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002002}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002003
Mathias Agopiancd60f992012-08-16 16:28:27 -07002004void SurfaceFlinger::doComposition() {
2005 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002006 ALOGV("doComposition");
2007
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002008 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002009 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002010 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002011 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002012 // transform the dirty region into this screen's coordinate space
2013 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002014
2015 // repaint the framebuffer (if needed)
2016 doDisplayComposition(hw, dirtyRegion);
2017
Mathias Agopiancd60f992012-08-16 16:28:27 -07002018 hw->dirtyRegion.clear();
2019 hw->flip(hw->swapRegion);
2020 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07002021 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002022 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002023 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002024}
2025
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002026void SurfaceFlinger::postFramebuffer()
2027{
Mathias Agopian841cde52012-03-01 15:44:37 -08002028 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002029 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002030
Mathias Agopiana44b0412011-10-16 18:46:35 -07002031 const nsecs_t now = systemTime();
2032 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002033
Dan Stoza9e56aa02015-11-02 13:00:03 -08002034 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2035 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002036 if (!displayDevice->isDisplayOn()) {
2037 continue;
2038 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002039 const auto hwcId = displayDevice->getHwcDisplayId();
2040 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08002041 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002042 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002043 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002044 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002045 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002046 // The layer buffer from the previous frame (if any) is released
2047 // by HWC only when the release fence from this frame (if any) is
2048 // signaled. Always get the release fence from HWC first.
2049 auto hwcLayer = layer->getHwcLayer(hwcId);
2050 sp<Fence> releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
2051
2052 // If the layer was client composited in the previous frame, we
2053 // need to merge with the previous client target acquire fence.
2054 // Since we do not track that, always merge with the current
2055 // client target acquire fence when it is available, even though
2056 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002057 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002058 releaseFence = Fence::merge("LayerRelease", releaseFence,
2059 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002060 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002061
Dan Stoza9e56aa02015-11-02 13:00:03 -08002062 layer->onLayerDisplayed(releaseFence);
2063 }
Chia-I Wu83806892017-11-16 10:50:20 -08002064
2065 // We've got a list of layers needing fences, that are disjoint with
2066 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2067 // supply them with the present fence.
2068 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
2069 sp<Fence> presentFence = mHwc->getPresentFence(hwcId);
2070 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2071 layer->onLayerDisplayed(presentFence);
2072 }
2073 }
2074
Dan Stoza9e56aa02015-11-02 13:00:03 -08002075 if (hwcId >= 0) {
2076 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002077 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002078 }
2079
Mathias Agopiana44b0412011-10-16 18:46:35 -07002080 mLastSwapBufferTime = systemTime() - now;
2081 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002082
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002083 // |mStateLock| not needed as we are on the main thread
2084 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002085 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2086 logFrameStats();
2087 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002088}
2089
Mathias Agopian87baae12012-07-31 12:38:26 -07002090void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002091{
Mathias Agopian841cde52012-03-01 15:44:37 -08002092 ATRACE_CALL();
2093
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002094 // here we keep a copy of the drawing state (that is the state that's
2095 // going to be overwritten by handleTransactionLocked()) outside of
2096 // mStateLock so that the side-effects of the State assignment
2097 // don't happen with mStateLock held (which can cause deadlocks).
2098 State drawingState(mDrawingState);
2099
Mathias Agopianca4d3602011-05-19 15:38:14 -07002100 Mutex::Autolock _l(mStateLock);
2101 const nsecs_t now = systemTime();
2102 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002103
Mathias Agopianca4d3602011-05-19 15:38:14 -07002104 // Here we're guaranteed that some transaction flags are set
2105 // so we can call handleTransactionLocked() unconditionally.
2106 // We call getTransactionFlags(), which will also clear the flags,
2107 // with mStateLock held to guarantee that mCurrentState won't change
2108 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002109
Mathias Agopiane57f2922012-08-09 16:29:12 -07002110 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002111 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002112
Mathias Agopianca4d3602011-05-19 15:38:14 -07002113 mLastTransactionTime = systemTime() - now;
2114 mDebugInTransaction = 0;
2115 invalidateHwcGeometry();
2116 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002117}
2118
Mathias Agopian87baae12012-07-31 12:38:26 -07002119void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002120{
Dan Stoza7dde5992015-05-22 09:51:44 -07002121 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002122 mCurrentState.traverseInZOrder([](Layer* layer) {
2123 layer->notifyAvailableFrames();
2124 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002125
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002126 /*
2127 * Traversal of the children
2128 * (perform the transaction for each of them if needed)
2129 */
2130
Mathias Agopian3559b072012-08-15 13:46:03 -07002131 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002132 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002133 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002134 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002135
2136 const uint32_t flags = layer->doTransaction(0);
2137 if (flags & Layer::eVisibleRegion)
2138 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002139 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002140 }
2141
2142 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002143 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002144 */
2145
Mathias Agopiane57f2922012-08-09 16:29:12 -07002146 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002147 // here we take advantage of Vector's copy-on-write semantics to
2148 // improve performance by skipping the transaction entirely when
2149 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07002150 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2151 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002152 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002153 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07002154 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07002155 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07002156
2157 // find the displays that were removed
2158 // (ie: in drawing state but not in current state)
2159 // also handle displays that changed
2160 // (ie: displays that are in both lists)
2161 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002162 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2163 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002164 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002165 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07002166 // Call makeCurrent() on the primary display so we can
2167 // be sure that nothing associated with this display
2168 // is current.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002169 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
Chia-I Wu7f402902017-11-09 12:51:10 -08002170 defaultDisplay->makeCurrent();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002171 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
Jesse Hall02d86562013-03-25 14:43:23 -07002172 if (hw != NULL)
2173 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07002174 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08002175 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07002176 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07002177 } else {
2178 ALOGW("trying to remove the main display");
2179 }
2180 } else {
2181 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07002182 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002183 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08002184 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2185 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07002186 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002187 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07002188 // recreating the DisplayDevice, so we just remove it
2189 // from the drawing state, so that it get re-added
2190 // below.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002191 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
Jesse Hall02d86562013-03-25 14:43:23 -07002192 if (hw != NULL)
2193 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07002194 mDisplays.removeItem(display);
2195 mDrawingState.displays.removeItemsAt(i);
2196 dc--; i--;
2197 // at this point we must loop to the next item
2198 continue;
2199 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002200
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002201 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07002202 if (disp != NULL) {
2203 if (state.layerStack != draw[i].layerStack) {
2204 disp->setLayerStack(state.layerStack);
2205 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002206 if ((state.orientation != draw[i].orientation)
2207 || (state.viewport != draw[i].viewport)
2208 || (state.frame != draw[i].frame))
2209 {
2210 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002211 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07002212 }
Michael Lentine47e45402014-07-18 15:34:25 -07002213 if (state.width != draw[i].width || state.height != draw[i].height) {
2214 disp->setDisplaySize(state.width, state.height);
2215 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002216 }
2217 }
2218 }
2219
2220 // find displays that were added
2221 // (ie: in current state but not in drawing state)
2222 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002223 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002224 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002225
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002226 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002227 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002228 sp<IGraphicBufferProducer> bqProducer;
2229 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian0556d792017-03-22 15:49:32 -07002230 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002231
Dan Stoza9e56aa02015-11-02 13:00:03 -08002232 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002233 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002234 // Virtual displays without a surface are dormant:
2235 // they have external state (layer stack, projection,
2236 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002237 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002238
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002239 // Allow VR composer to use virtual displays.
Steven Thomasb02664d2017-07-26 18:48:28 -07002240 if (mUseHwcVirtualDisplays || mHwc->isUsingVrComposer()) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002241 int width = 0;
2242 int status = state.surface->query(
2243 NATIVE_WINDOW_WIDTH, &width);
2244 ALOGE_IF(status != NO_ERROR,
2245 "Unable to query width (%d)", status);
2246 int height = 0;
2247 status = state.surface->query(
2248 NATIVE_WINDOW_HEIGHT, &height);
2249 ALOGE_IF(status != NO_ERROR,
2250 "Unable to query height (%d)", status);
2251 int intFormat = 0;
2252 status = state.surface->query(
2253 NATIVE_WINDOW_FORMAT, &intFormat);
2254 ALOGE_IF(status != NO_ERROR,
2255 "Unable to query format (%d)", status);
2256 auto format = static_cast<android_pixel_format_t>(
2257 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002258
Dan Stoza8cf150a2016-08-02 10:27:31 -07002259 mHwc->allocateVirtualDisplay(width, height, &format,
2260 &hwcId);
2261 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002262
Dan Stoza5cf424b2016-05-20 14:02:39 -07002263 // TODO: Plumb requested format back up to consumer
2264
Dan Stoza9e56aa02015-11-02 13:00:03 -08002265 sp<VirtualDisplaySurface> vds =
2266 new VirtualDisplaySurface(*mHwc,
2267 hwcId, state.surface, bqProducer,
2268 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002269
2270 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002271 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002272 }
2273 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002274 ALOGE_IF(state.surface!=NULL,
2275 "adding a supported display, but rendering "
2276 "surface is provided (%p), ignoring it",
2277 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002278
2279 hwcId = state.type;
2280 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2281 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002282 }
2283
2284 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002285 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002286 sp<DisplayDevice> hw =
2287 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2288 dispSurface, producer,
2289 mRenderEngine->getEGLConfig(),
2290 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002291 hw->setLayerStack(state.layerStack);
2292 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002293 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002294 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002295 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002296 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002297 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002298 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002299 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002300 }
2301 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002302 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002303 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002304
Mathias Agopian84300952012-11-21 16:02:13 -08002305 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2306 // The transform hint might have changed for some layers
2307 // (either because a display has changed, or because a layer
2308 // as changed).
2309 //
2310 // Walk through all the layers in currentLayers,
2311 // and update their transform hint.
2312 //
2313 // If a layer is visible only on a single display, then that
2314 // display is used to calculate the hint, otherwise we use the
2315 // default display.
2316 //
2317 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2318 // the hint is set before we acquire a buffer from the surface texture.
2319 //
2320 // NOTE: layer transactions have taken place already, so we use their
2321 // drawing state. However, SurfaceFlinger's own transaction has not
2322 // happened yet, so we must use the current state layer list
2323 // (soon to become the drawing state list).
2324 //
2325 sp<const DisplayDevice> disp;
2326 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002327 bool first = true;
2328 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002329 // NOTE: we rely on the fact that layers are sorted by
2330 // layerStack first (so we don't have to traverse the list
2331 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002332 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002333 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002334 currentlayerStack = layerStack;
2335 // figure out if this layerstack is mirrored
2336 // (more than one display) if so, pick the default display,
2337 // if not, pick the only display it's on.
2338 disp.clear();
2339 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2340 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002341 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian84300952012-11-21 16:02:13 -08002342 if (disp == NULL) {
George Burgess IV406a2852017-08-29 17:57:25 -07002343 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002344 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002345 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002346 break;
2347 }
2348 }
2349 }
2350 }
Chet Haase91d25932013-04-11 15:24:55 -07002351 if (disp == NULL) {
2352 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2353 // redraw after transform hint changes. See bug 8508397.
2354
2355 // could be null when this layer is using a layerStack
2356 // that is not visible on any display. Also can occur at
2357 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002358 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002359 }
Chet Haase91d25932013-04-11 15:24:55 -07002360 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002361
2362 first = false;
2363 });
Mathias Agopian84300952012-11-21 16:02:13 -08002364 }
2365
2366
Mathias Agopian3559b072012-08-15 13:46:03 -07002367 /*
2368 * Perform our own transaction if needed
2369 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002370
2371 if (mLayersAdded) {
2372 mLayersAdded = false;
2373 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002374 mVisibleRegionsDirty = true;
2375 }
2376
2377 // some layers might have been removed, so
2378 // we need to update the regions they're exposing.
2379 if (mLayersRemoved) {
2380 mLayersRemoved = false;
2381 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002382 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002383 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002384 // this layer is not visible anymore
2385 // TODO: we could traverse the tree from front to back and
2386 // compute the actual visible region
2387 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002388 Region visibleReg;
2389 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002390 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002391 }
Robert Carr2047fae2016-11-28 14:09:09 -08002392 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002393 }
2394
2395 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002396
2397 updateCursorAsync();
2398}
2399
2400void SurfaceFlinger::updateCursorAsync()
2401{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002402 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2403 auto& displayDevice = mDisplays[displayId];
2404 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002405 continue;
2406 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002407
2408 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2409 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002410 }
2411 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002412}
2413
2414void SurfaceFlinger::commitTransaction()
2415{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002416 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002417 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002418 for (const auto& l : mLayersPendingRemoval) {
2419 recordBufferingStats(l->getName().string(),
2420 l->getOccupancyHistory(true));
2421 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002422 }
2423 mLayersPendingRemoval.clear();
2424 }
2425
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002426 // If this transaction is part of a window animation then the next frame
2427 // we composite should be considered an animation as well.
2428 mAnimCompositionPending = mAnimTransactionPending;
2429
Mathias Agopian4fec8732012-06-29 14:12:52 -07002430 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002431 mDrawingState.traverseInZOrder([](Layer* layer) {
2432 layer->commitChildList();
2433 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002434 mTransactionPending = false;
2435 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002436 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002437}
2438
Chia-I Wuab0c3192017-08-01 11:29:00 -07002439void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002440 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002441{
Mathias Agopian841cde52012-03-01 15:44:37 -08002442 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002443 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002444
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002445 Region aboveOpaqueLayers;
2446 Region aboveCoveredLayers;
2447 Region dirty;
2448
Mathias Agopian87baae12012-07-31 12:38:26 -07002449 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002450
Robert Carr2047fae2016-11-28 14:09:09 -08002451 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002452 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002453 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002454
Jesse Hall01e29052013-02-19 16:13:35 -08002455 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002456 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002457 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002458
Mathias Agopianab028732010-03-16 16:41:46 -07002459 /*
2460 * opaqueRegion: area of a surface that is fully opaque.
2461 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002462 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002463
2464 /*
2465 * visibleRegion: area of a surface that is visible on screen
2466 * and not fully transparent. This is essentially the layer's
2467 * footprint minus the opaque regions above it.
2468 * Areas covered by a translucent surface are considered visible.
2469 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002470 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002471
2472 /*
2473 * coveredRegion: area of a surface that is covered by all
2474 * visible regions above it (which includes the translucent areas).
2475 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002476 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002477
Jesse Halla8026d22012-09-25 13:25:04 -07002478 /*
2479 * transparentRegion: area of a surface that is hinted to be completely
2480 * transparent. This is only used to tell when the layer has no visible
2481 * non-transparent regions and can be removed from the layer list. It
2482 * does not affect the visibleRegion of this layer or any layers
2483 * beneath it. The hint may not be correct if apps don't respect the
2484 * SurfaceView restrictions (which, sadly, some don't).
2485 */
2486 Region transparentRegion;
2487
Mathias Agopianab028732010-03-16 16:41:46 -07002488
2489 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002490 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002491 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002492 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002493 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002494 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002495 if (!visibleRegion.isEmpty()) {
2496 // Remove the transparent area from the visible region
2497 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002498 if (tr.preserveRects()) {
2499 // transform the transparent region
2500 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002501 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002502 // transformation too complex, can't do the
2503 // transparent region optimization.
2504 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002505 }
Mathias Agopianab028732010-03-16 16:41:46 -07002506 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002507
Mathias Agopianab028732010-03-16 16:41:46 -07002508 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002509 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002510 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002511 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2512 // the opaque region is the layer's footprint
2513 opaqueRegion = visibleRegion;
2514 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002515 }
2516 }
2517
Mathias Agopianab028732010-03-16 16:41:46 -07002518 // Clip the covered region to the visible region
2519 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2520
2521 // Update aboveCoveredLayers for next (lower) layer
2522 aboveCoveredLayers.orSelf(visibleRegion);
2523
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002524 // subtract the opaque region covered by the layers above us
2525 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002526
2527 // compute this layer's dirty region
2528 if (layer->contentDirty) {
2529 // we need to invalidate the whole region
2530 dirty = visibleRegion;
2531 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002532 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002533 layer->contentDirty = false;
2534 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002535 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002536 * the exposed region consists of two components:
2537 * 1) what's VISIBLE now and was COVERED before
2538 * 2) what's EXPOSED now less what was EXPOSED before
2539 *
2540 * note that (1) is conservative, we start with the whole
2541 * visible region but only keep what used to be covered by
2542 * something -- which mean it may have been exposed.
2543 *
2544 * (2) handles areas that were not covered by anything but got
2545 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002546 */
Mathias Agopianab028732010-03-16 16:41:46 -07002547 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002548 const Region oldVisibleRegion = layer->visibleRegion;
2549 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002550 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2551 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002552 }
2553 dirty.subtractSelf(aboveOpaqueLayers);
2554
2555 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002556 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002557
Mathias Agopianab028732010-03-16 16:41:46 -07002558 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002559 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002560
Jesse Halla8026d22012-09-25 13:25:04 -07002561 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002562 layer->setVisibleRegion(visibleRegion);
2563 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002564 layer->setVisibleNonTransparentRegion(
2565 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002566 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002567
Mathias Agopian87baae12012-07-31 12:38:26 -07002568 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002569}
2570
Chia-I Wuab0c3192017-08-01 11:29:00 -07002571void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002572 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002573 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002574 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002575 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002576 }
2577 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002578}
2579
Dan Stoza6b9454d2014-11-07 16:00:59 -08002580bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002581{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002582 ALOGV("handlePageFlip");
2583
Brian Andersond6927fb2016-07-23 23:37:30 -07002584 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002585
Mathias Agopian4fec8732012-06-29 14:12:52 -07002586 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002587 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002588 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002589
2590 // Store the set of layers that need updates. This set must not change as
2591 // buffers are being latched, as this could result in a deadlock.
2592 // Example: Two producers share the same command stream and:
2593 // 1.) Layer 0 is latched
2594 // 2.) Layer 0 gets a new frame
2595 // 2.) Layer 1 gets a new frame
2596 // 3.) Layer 1 is latched.
2597 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2598 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002599 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002600 if (layer->hasQueuedFrame()) {
2601 frameQueued = true;
2602 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002603 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002604 } else {
2605 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002606 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002607 } else {
2608 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002609 }
Robert Carr2047fae2016-11-28 14:09:09 -08002610 });
2611
Dan Stoza9e56aa02015-11-02 13:00:03 -08002612 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002613 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002614 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002615 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002616 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002617 newDataLatched = true;
2618 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002619 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002620
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002621 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002622
2623 // If we will need to wake up at some time in the future to deal with a
2624 // queued frame that shouldn't be displayed during this vsync period, wake
2625 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002626 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002627 signalLayerUpdate();
2628 }
2629
2630 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002631 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002632}
2633
Mathias Agopianad456f92011-01-13 17:53:01 -08002634void SurfaceFlinger::invalidateHwcGeometry()
2635{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002636 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002637}
2638
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002639
Fabien Sanglard830b8472016-11-30 16:35:58 -08002640void SurfaceFlinger::doDisplayComposition(
2641 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002642 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002643{
Dan Stoza71433162014-02-04 16:22:36 -08002644 // We only need to actually compose the display if:
2645 // 1) It is being handled by hardware composer, which may need this to
2646 // keep its virtual display state machine in sync, or
2647 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002648 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002649 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002650 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002651 return;
2652 }
2653
Dan Stoza9e56aa02015-11-02 13:00:03 -08002654 ALOGV("doDisplayComposition");
2655
Mathias Agopian87baae12012-07-31 12:38:26 -07002656 Region dirtyRegion(inDirtyRegion);
2657
Mathias Agopianb8a55602009-06-26 19:06:36 -07002658 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002659 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002660
Fabien Sanglard830b8472016-11-30 16:35:58 -08002661 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002662 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002663 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2664 // takes a rectangle, we must make sure to update that whole
2665 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002666 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002667 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002668 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002669 // We need to redraw the rectangle that will be updated
2670 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002671 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002672 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002673 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002674 } else {
2675 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002676 dirtyRegion.set(displayDevice->bounds());
2677 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002678 }
2679 }
2680
Fabien Sanglard830b8472016-11-30 16:35:58 -08002681 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002682
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002683 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002684 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002685
2686 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002687 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002688}
2689
Dan Stoza9e56aa02015-11-02 13:00:03 -08002690bool SurfaceFlinger::doComposeSurfaces(
2691 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002692{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002693 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002694
chaviwa76b2712017-09-20 12:02:26 -07002695 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002696 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002697
2698 mat4 oldColorMatrix;
2699 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2700 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2701 if (applyColorMatrix) {
2702 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2703 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2704 }
2705
Dan Stoza9e56aa02015-11-02 13:00:03 -08002706 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2707 if (hasClientComposition) {
2708 ALOGV("hasClientComposition");
2709
Romain Guy54f154a2017-10-24 21:40:32 +01002710 mRenderEngine->setWideColor(
2711 displayDevice->getWideColorSupport() && !mForceNativeColorMode);
2712 mRenderEngine->setColorMode(mForceNativeColorMode ?
2713 HAL_COLOR_MODE_NATIVE : displayDevice->getActiveColorMode());
Chia-I Wu7f402902017-11-09 12:51:10 -08002714 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002715 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002716 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002717 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002718
2719 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002720 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002721 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2722 }
2723 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002724 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002725
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002726 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002727 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2728 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002729 // when using overlays, we assume a fully transparent framebuffer
2730 // NOTE: we could reduce how much we need to clear, for instance
2731 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002732 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002733 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002734 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002735 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002736 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002737 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002738
2739 // we remove the scissor part
2740 // we're left with the letterbox region
2741 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002742 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002743
2744 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002745 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002746
2747 // but limit it to the dirty region
2748 region.andSelf(dirty);
2749
Mathias Agopianb9494d52012-04-18 02:28:45 -07002750 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002751 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002752 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002753 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002754 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002755 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002756
Dan Stoza9e56aa02015-11-02 13:00:03 -08002757 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002758 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002759 // scissor on the main display. It should never be needed
2760 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002761 const Rect& bounds(displayDevice->getBounds());
2762 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002763 if (scissor != bounds) {
2764 // scissor doesn't match the screen's dimensions, so we
2765 // need to clear everything outside of it and enable
2766 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002767
Mathias Agopianf45c5102012-10-24 16:29:17 -07002768 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002769 const uint32_t height = displayDevice->getHeight();
2770 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002771 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002772 }
2773 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002774 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002775
Mathias Agopian85d751c2012-08-29 16:59:24 -07002776 /*
2777 * and then, render the layers targeted at the framebuffer
2778 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002779
Dan Stoza9e56aa02015-11-02 13:00:03 -08002780 ALOGV("Rendering client layers");
2781 const Transform& displayTransform = displayDevice->getTransform();
2782 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002783 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002784 bool firstLayer = true;
2785 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2786 const Region clip(dirty.intersect(
2787 displayTransform.transform(layer->visibleRegion)));
2788 ALOGV("Layer: %s", layer->getName().string());
2789 ALOGV(" Composition type: %s",
2790 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002791 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002792 switch (layer->getCompositionType(hwcId)) {
2793 case HWC2::Composition::Cursor:
2794 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002795 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002796 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002797 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002798 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002799 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002800 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002801 // never clear the very first layer since we're
2802 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002803 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002804 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002805 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002806 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002807 case HWC2::Composition::Client: {
chaviwa76b2712017-09-20 12:02:26 -07002808 layer->draw(renderArea, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002809 break;
2810 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002811 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002812 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002813 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002814 } else {
2815 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002816 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002817 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002818 }
2819 } else {
2820 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002821 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002822 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002823 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002824 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07002825 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002826 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002827 }
2828 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002829
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002830 if (applyColorMatrix) {
2831 getRenderEngine().setupColorTransform(oldColorMatrix);
2832 }
2833
Mathias Agopianf45c5102012-10-24 16:29:17 -07002834 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002835 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002836 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002837}
2838
Fabien Sanglard830b8472016-11-30 16:35:58 -08002839void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2840 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002841 RenderEngine& engine(getRenderEngine());
2842 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002843}
2844
Dan Stoza7d89d062015-04-30 13:29:25 -07002845status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002846 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002847 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002848 const sp<Layer>& lbc,
2849 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002850{
Dan Stoza7d89d062015-04-30 13:29:25 -07002851 // add this layer to the current state list
2852 {
2853 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002854 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002855 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2856 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002857 return NO_MEMORY;
2858 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002859 if (parent == nullptr) {
2860 mCurrentState.layersSortedByZ.add(lbc);
2861 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08002862 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002863 ALOGE("addClientLayer called with a removed parent");
2864 return NAME_NOT_FOUND;
2865 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002866 parent->addChild(lbc);
2867 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002868
Dan Stoza7d89d062015-04-30 13:29:25 -07002869 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002870 mLayersAdded = true;
2871 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002872 }
2873
Mathias Agopian96f08192010-06-02 23:28:45 -07002874 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002875 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002876
Dan Stoza7d89d062015-04-30 13:29:25 -07002877 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002878}
2879
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002880status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002881 Mutex::Autolock _l(mStateLock);
2882
chaviw8b3871a2017-11-01 17:41:01 -07002883 if (layer->isPendingRemoval()) {
2884 return NO_ERROR;
2885 }
2886
Robert Carr1f0a16a2016-10-24 16:27:39 -07002887 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002888 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002889 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002890 if (topLevelOnly) {
2891 return NO_ERROR;
2892 }
2893
Chia-I Wu98f1c102017-05-30 14:54:08 -07002894 sp<Layer> ancestor = p;
2895 while (ancestor->getParent() != nullptr) {
2896 ancestor = ancestor->getParent();
2897 }
2898 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2899 ALOGE("removeLayer called with a layer whose parent has been removed");
2900 return NAME_NOT_FOUND;
2901 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002902
2903 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002904 } else {
2905 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002906 }
2907
Robert Carr136e2f62017-02-08 17:54:29 -08002908 // As a matter of normal operation, the LayerCleaner will produce a second
2909 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2910 // so we will succeed in promoting it, but it's already been removed
2911 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2912 // otherwise something has gone wrong and we are leaking the layer.
2913 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002914 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2915 layer->getName().string(),
2916 (p != nullptr) ? p->getName().string() : "no-parent");
2917 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002918 } else if (index < 0) {
2919 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002920 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002921
Chia-I Wuc6657022017-08-15 11:18:17 -07002922 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002923 mLayersPendingRemoval.add(layer);
2924 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002925 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002926 setTransactionFlags(eTransactionNeeded);
2927 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002928}
2929
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002930uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002931 return android_atomic_release_load(&mTransactionFlags);
2932}
2933
Mathias Agopian3f844832013-08-07 21:24:32 -07002934uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002935 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2936}
2937
Mathias Agopian3f844832013-08-07 21:24:32 -07002938uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002939 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2940 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002941 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002942 }
2943 return old;
2944}
2945
Mathias Agopian8b33f032012-07-24 20:43:54 -07002946void SurfaceFlinger::setTransactionState(
2947 const Vector<ComposerState>& state,
2948 const Vector<DisplayState>& displays,
2949 uint32_t flags)
2950{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002951 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002952 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002953 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002954
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002955 if (flags & eAnimation) {
2956 // For window updates that are part of an animation we must wait for
2957 // previous animation "frames" to be handled.
2958 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002959 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002960 if (CC_UNLIKELY(err != NO_ERROR)) {
2961 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002962 // caller after a few seconds.
2963 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2964 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002965 mAnimTransactionPending = false;
2966 break;
2967 }
2968 }
2969 }
2970
Mathias Agopiane57f2922012-08-09 16:29:12 -07002971 size_t count = displays.size();
2972 for (size_t i=0 ; i<count ; i++) {
2973 const DisplayState& s(displays[i]);
2974 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002975 }
2976
Mathias Agopiane57f2922012-08-09 16:29:12 -07002977 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002978 for (size_t i=0 ; i<count ; i++) {
2979 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002980 // Here we need to check that the interface we're given is indeed
2981 // one of our own. A malicious client could give us a NULL
2982 // IInterface, or one of its own or even one of our own but a
2983 // different type. All these situations would cause us to crash.
2984 //
2985 // NOTE: it would be better to use RTTI as we could directly check
2986 // that we have a Client*. however, RTTI is disabled in Android.
2987 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002988 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002989 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002990 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002991 sp<Client> client( static_cast<Client *>(s.client.get()) );
2992 transactionFlags |= setClientStateLocked(client, s.state);
2993 }
2994 }
2995 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002996 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002997
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02002998 // If a synchronous transaction is explicitly requested without any changes, force a transaction
2999 // anyway. This can be used as a flush mechanism for previous async transactions.
3000 // Empty animation transaction can be used to simulate back-pressure, so also force a
3001 // transaction for empty animation transactions.
3002 if (transactionFlags == 0 &&
3003 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003004 transactionFlags = eTransactionNeeded;
3005 }
3006
Mathias Agopian386aa982011-11-07 21:58:03 -08003007 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07003008 if (mInterceptor.isEnabled()) {
3009 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
3010 }
Irvel468051e2016-06-13 16:44:44 -07003011
Mathias Agopian386aa982011-11-07 21:58:03 -08003012 // this triggers the transaction
3013 setTransactionFlags(transactionFlags);
3014
3015 // if this is a synchronous transaction, wait for it to take effect
3016 // before returning.
3017 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003018 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003019 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003020 if (flags & eAnimation) {
3021 mAnimTransactionPending = true;
3022 }
3023 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003024 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3025 if (CC_UNLIKELY(err != NO_ERROR)) {
3026 // just in case something goes wrong in SF, return to the
3027 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003028 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3029 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003030 break;
3031 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003032 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003033 }
3034}
3035
Mathias Agopiane57f2922012-08-09 16:29:12 -07003036uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3037{
Jesse Hall9a143922012-10-04 16:29:19 -07003038 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3039 if (dpyIdx < 0)
3040 return 0;
3041
Mathias Agopiane57f2922012-08-09 16:29:12 -07003042 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003043 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003044 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003045 const uint32_t what = s.what;
3046 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003047 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003048 disp.surface = s.surface;
3049 flags |= eDisplayTransactionNeeded;
3050 }
3051 }
3052 if (what & DisplayState::eLayerStackChanged) {
3053 if (disp.layerStack != s.layerStack) {
3054 disp.layerStack = s.layerStack;
3055 flags |= eDisplayTransactionNeeded;
3056 }
3057 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003058 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003059 if (disp.orientation != s.orientation) {
3060 disp.orientation = s.orientation;
3061 flags |= eDisplayTransactionNeeded;
3062 }
3063 if (disp.frame != s.frame) {
3064 disp.frame = s.frame;
3065 flags |= eDisplayTransactionNeeded;
3066 }
3067 if (disp.viewport != s.viewport) {
3068 disp.viewport = s.viewport;
3069 flags |= eDisplayTransactionNeeded;
3070 }
3071 }
Michael Lentine47e45402014-07-18 15:34:25 -07003072 if (what & DisplayState::eDisplaySizeChanged) {
3073 if (disp.width != s.width) {
3074 disp.width = s.width;
3075 flags |= eDisplayTransactionNeeded;
3076 }
3077 if (disp.height != s.height) {
3078 disp.height = s.height;
3079 flags |= eDisplayTransactionNeeded;
3080 }
3081 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003082 }
3083 return flags;
3084}
3085
3086uint32_t SurfaceFlinger::setClientStateLocked(
3087 const sp<Client>& client,
3088 const layer_state_t& s)
3089{
Mathias Agopian13127d82013-03-05 17:47:11 -08003090 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003091 if (layer == nullptr) {
3092 return 0;
3093 }
3094
3095 if (layer->isPendingRemoval()) {
3096 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3097 return 0;
3098 }
3099
3100 uint32_t flags = 0;
3101
3102 const uint32_t what = s.what;
3103 bool geometryAppliesWithResize =
3104 what & layer_state_t::eGeometryAppliesWithResize;
3105 if (what & layer_state_t::ePositionChanged) {
3106 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3107 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003108 }
chaviw8b3871a2017-11-01 17:41:01 -07003109 }
3110 if (what & layer_state_t::eLayerChanged) {
3111 // NOTE: index needs to be calculated before we update the state
3112 const auto& p = layer->getParent();
3113 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003114 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003115 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003116 mCurrentState.layersSortedByZ.removeAt(idx);
3117 mCurrentState.layersSortedByZ.add(layer);
3118 // we need traversal (state changed)
3119 // AND transaction (list changed)
3120 flags |= eTransactionNeeded|eTraversalNeeded;
3121 }
chaviw8b3871a2017-11-01 17:41:01 -07003122 } else {
3123 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003124 flags |= eTransactionNeeded|eTraversalNeeded;
3125 }
3126 }
chaviw8b3871a2017-11-01 17:41:01 -07003127 }
3128 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003129 // NOTE: index needs to be calculated before we update the state
3130 const auto& p = layer->getParent();
3131 if (p == nullptr) {
3132 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3133 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3134 mCurrentState.layersSortedByZ.removeAt(idx);
3135 mCurrentState.layersSortedByZ.add(layer);
3136 // we need traversal (state changed)
3137 // AND transaction (list changed)
3138 flags |= eTransactionNeeded|eTraversalNeeded;
3139 }
3140 } else {
3141 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3142 flags |= eTransactionNeeded|eTraversalNeeded;
3143 }
chaviw8b3871a2017-11-01 17:41:01 -07003144 }
3145 }
3146 if (what & layer_state_t::eSizeChanged) {
3147 if (layer->setSize(s.w, s.h)) {
3148 flags |= eTraversalNeeded;
3149 }
3150 }
3151 if (what & layer_state_t::eAlphaChanged) {
3152 if (layer->setAlpha(s.alpha))
3153 flags |= eTraversalNeeded;
3154 }
3155 if (what & layer_state_t::eColorChanged) {
3156 if (layer->setColor(s.color))
3157 flags |= eTraversalNeeded;
3158 }
3159 if (what & layer_state_t::eMatrixChanged) {
3160 if (layer->setMatrix(s.matrix))
3161 flags |= eTraversalNeeded;
3162 }
3163 if (what & layer_state_t::eTransparentRegionChanged) {
3164 if (layer->setTransparentRegionHint(s.transparentRegion))
3165 flags |= eTraversalNeeded;
3166 }
3167 if (what & layer_state_t::eFlagsChanged) {
3168 if (layer->setFlags(s.flags, s.mask))
3169 flags |= eTraversalNeeded;
3170 }
3171 if (what & layer_state_t::eCropChanged) {
3172 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3173 flags |= eTraversalNeeded;
3174 }
3175 if (what & layer_state_t::eFinalCropChanged) {
3176 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3177 flags |= eTraversalNeeded;
3178 }
3179 if (what & layer_state_t::eLayerStackChanged) {
3180 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3181 // We only allow setting layer stacks for top level layers,
3182 // everything else inherits layer stack from its parent.
3183 if (layer->hasParent()) {
3184 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3185 layer->getName().string());
3186 } else if (idx < 0) {
3187 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3188 "that also does not appear in the top level layer list. Something"
3189 " has gone wrong.", layer->getName().string());
3190 } else if (layer->setLayerStack(s.layerStack)) {
3191 mCurrentState.layersSortedByZ.removeAt(idx);
3192 mCurrentState.layersSortedByZ.add(layer);
3193 // we need traversal (state changed)
3194 // AND transaction (list changed)
3195 flags |= eTransactionNeeded|eTraversalNeeded;
3196 }
3197 }
3198 if (what & layer_state_t::eDeferTransaction) {
3199 if (s.barrierHandle != nullptr) {
3200 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3201 } else if (s.barrierGbp != nullptr) {
3202 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3203 if (authenticateSurfaceTextureLocked(gbp)) {
3204 const auto& otherLayer =
3205 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3206 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3207 } else {
3208 ALOGE("Attempt to defer transaction to to an"
3209 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003210 }
3211 }
chaviw8b3871a2017-11-01 17:41:01 -07003212 // We don't trigger a traversal here because if no other state is
3213 // changed, we don't want this to cause any more work
3214 }
3215 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003216 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003217 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003218 if (!hadParent) {
3219 mCurrentState.layersSortedByZ.remove(layer);
3220 }
chaviw8b3871a2017-11-01 17:41:01 -07003221 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003222 }
chaviw8b3871a2017-11-01 17:41:01 -07003223 }
3224 if (what & layer_state_t::eReparentChildren) {
3225 if (layer->reparentChildren(s.reparentHandle)) {
3226 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003227 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003228 }
chaviw8b3871a2017-11-01 17:41:01 -07003229 if (what & layer_state_t::eDetachChildren) {
3230 layer->detachChildren();
3231 }
3232 if (what & layer_state_t::eOverrideScalingModeChanged) {
3233 layer->setOverrideScalingMode(s.overrideScalingMode);
3234 // We don't trigger a traversal here because if no other state is
3235 // changed, we don't want this to cause any more work
3236 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003237 return flags;
3238}
3239
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003240status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003241 const String8& name,
3242 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003243 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003244 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3245 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003246{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003247 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003248 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003249 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003250 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003251 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003252
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003253 status_t result = NO_ERROR;
3254
3255 sp<Layer> layer;
3256
Cody Northropbc755282017-03-31 12:00:08 -06003257 String8 uniqueName = getUniqueLayerName(name);
3258
Mathias Agopian3165cc22012-08-08 19:42:09 -07003259 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3260 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003261 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003262 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003263 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003264
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003265 break;
chaviw13fdc492017-06-27 12:40:18 -07003266 case ISurfaceComposerClient::eFXSurfaceColor:
3267 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003268 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003269 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003270 break;
3271 default:
3272 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003273 break;
3274 }
3275
Dan Stoza7d89d062015-04-30 13:29:25 -07003276 if (result != NO_ERROR) {
3277 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003278 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003279
Chia-I Wuab0c3192017-08-01 11:29:00 -07003280 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3281 // TODO b/64227542
3282 if (windowType == 441731) {
3283 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3284 layer->setPrimaryDisplayOnly();
3285 }
3286
Albert Chaulk479c60c2017-01-27 14:21:34 -05003287 layer->setInfo(windowType, ownerUid);
3288
Robert Carr1f0a16a2016-10-24 16:27:39 -07003289 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003290 if (result != NO_ERROR) {
3291 return result;
3292 }
Irvelffc9efc2016-07-27 15:16:37 -07003293 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003294
3295 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003296 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003297}
3298
Cody Northropbc755282017-03-31 12:00:08 -06003299String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3300{
3301 bool matchFound = true;
3302 uint32_t dupeCounter = 0;
3303
3304 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3305 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3306
3307 // Loop over layers until we're sure there is no matching name
3308 while (matchFound) {
3309 matchFound = false;
3310 mDrawingState.traverseInZOrder([&](Layer* layer) {
3311 if (layer->getName() == uniqueName) {
3312 matchFound = true;
3313 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3314 }
3315 });
3316 }
3317
3318 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3319
3320 return uniqueName;
3321}
3322
David Sodman0c69cad2017-08-21 12:12:51 -07003323status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003324 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3325 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003326{
3327 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003328 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003329 case PIXEL_FORMAT_TRANSPARENT:
3330 case PIXEL_FORMAT_TRANSLUCENT:
3331 format = PIXEL_FORMAT_RGBA_8888;
3332 break;
3333 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003334 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003335 break;
3336 }
3337
David Sodman0c69cad2017-08-21 12:12:51 -07003338 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3339 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003340 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003341 *handle = layer->getHandle();
3342 *gbp = layer->getProducer();
3343 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003344 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003345
David Sodman0c69cad2017-08-21 12:12:51 -07003346 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003347 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003348}
3349
chaviw13fdc492017-06-27 12:40:18 -07003350status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003351 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003352 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003353{
chaviw13fdc492017-06-27 12:40:18 -07003354 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003355 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003356 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003357}
3358
Mathias Agopianac9fa422013-02-11 16:40:36 -08003359status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003360{
Robert Carr9524cb32017-02-13 11:32:32 -08003361 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003362 status_t err = NO_ERROR;
3363 sp<Layer> l(client->getLayerUser(handle));
3364 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003365 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003366 err = removeLayer(l);
3367 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3368 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003369 }
3370 return err;
3371}
3372
Mathias Agopian13127d82013-03-05 17:47:11 -08003373status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003374{
Mathias Agopian67106042013-03-14 19:18:13 -07003375 // called by ~LayerCleaner() when all references to the IBinder (handle)
3376 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003377 sp<Layer> l = layer.promote();
3378 if (l == nullptr) {
3379 // The layer has already been removed, carry on
3380 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003381 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003382 // If we have a parent, then we can continue to live as long as it does.
3383 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003384}
3385
Mathias Agopianb60314a2012-04-10 22:09:54 -07003386// ---------------------------------------------------------------------------
3387
Andy McFadden13a082e2012-08-24 10:16:42 -07003388void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003389 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003390 Vector<ComposerState> state;
3391 Vector<DisplayState> displays;
3392 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003393 d.what = DisplayState::eDisplayProjectionChanged |
3394 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003395 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003396 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003397 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003398 d.frame.makeInvalid();
3399 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003400 d.width = 0;
3401 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003402 displays.add(d);
3403 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003404 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3405 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003406
Dan Stoza9e56aa02015-11-02 13:00:03 -08003407 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3408 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003409 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003410
Brian Andersond0010582017-03-07 13:20:31 -08003411 // Use phase of 0 since phase is not known.
3412 // Use latency of 0, which will snap to the ideal latency.
3413 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003414}
3415
3416void SurfaceFlinger::initializeDisplays() {
3417 class MessageScreenInitialized : public MessageBase {
3418 SurfaceFlinger* flinger;
3419 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003420 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003421 virtual bool handler() {
3422 flinger->onInitializeDisplays();
3423 return true;
3424 }
3425 };
3426 sp<MessageBase> msg = new MessageScreenInitialized(this);
3427 postMessageAsync(msg); // we may be called from main thread, use async message
3428}
3429
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003430void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003431 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003432 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3433 this);
3434 int32_t type = hw->getDisplayType();
3435 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003436
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003437 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003438 return;
3439 }
3440
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003441 hw->setPowerMode(mode);
3442 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3443 ALOGW("Trying to set power mode for virtual display");
3444 return;
3445 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003446
Irvelffc9efc2016-07-27 15:16:37 -07003447 if (mInterceptor.isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003448 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003449 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3450 if (idx < 0) {
3451 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3452 return;
3453 }
3454 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3455 }
3456
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003457 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003458 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003459 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003460 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3461 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003462 // FIXME: eventthread only knows about the main display right now
3463 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003464 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003465 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003466
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003467 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003468 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003469 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003470
3471 struct sched_param param = {0};
3472 param.sched_priority = 1;
3473 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3474 ALOGW("Couldn't set SCHED_FIFO on display on");
3475 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003476 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003477 // Turn off the display
3478 struct sched_param param = {0};
3479 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3480 ALOGW("Couldn't set SCHED_OTHER on display off");
3481 }
3482
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003483 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3484 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003485 disableHardwareVsync(true); // also cancels any in-progress resync
3486
Mathias Agopiancde87a32012-09-13 14:09:01 -07003487 // FIXME: eventthread only knows about the main display right now
3488 mEventThread->onScreenReleased();
3489 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003490
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003491 getHwComposer().setPowerMode(type, mode);
3492 mVisibleRegionsDirty = true;
3493 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003494 } else if (mode == HWC_POWER_MODE_DOZE ||
3495 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003496 // Update display while dozing
3497 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003498 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3499 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003500 // FIXME: eventthread only knows about the main display right now
3501 mEventThread->onScreenAcquired();
3502 resyncToHardwareVsync(true);
3503 }
3504 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3505 // Leave display going to doze
3506 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3507 disableHardwareVsync(true); // also cancels any in-progress resync
3508 // FIXME: eventthread only knows about the main display right now
3509 mEventThread->onScreenReleased();
3510 }
3511 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003512 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003513 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003514 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003515 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003516}
3517
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003518void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3519 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003520 SurfaceFlinger& mFlinger;
3521 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003522 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003523 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003524 MessageSetPowerMode(SurfaceFlinger& flinger,
3525 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3526 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003527 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003528 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003529 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003530 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003531 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003532 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003533 ALOGW("Attempt to set power mode = %d for virtual display",
3534 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003535 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003536 mFlinger.setPowerModeInternal(
3537 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003538 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003539 return true;
3540 }
3541 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003542 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003543 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003544}
3545
3546// ---------------------------------------------------------------------------
3547
Vishnu Nair6a408532017-10-24 09:11:27 -07003548status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003549 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003550
Mathias Agopianbd115332013-04-18 16:41:04 -07003551 IPCThreadState* ipc = IPCThreadState::self();
3552 const int pid = ipc->getCallingPid();
3553 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003554
Mathias Agopianbd115332013-04-18 16:41:04 -07003555 if ((uid != AID_SHELL) &&
3556 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003557 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003558 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003559 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003560 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003561 // (this would indicate SF is stuck, but we want to be able to
3562 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003563 status_t err = mStateLock.timedLock(s2ns(1));
3564 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003565 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003566 result.appendFormat(
3567 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3568 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003569 }
3570
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003571 bool dumpAll = true;
3572 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003573 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003574
3575 if (asProto) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003576 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviwa3d7bd32017-11-03 09:41:53 -07003577 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3578 dumpAll = false;
3579 }
3580
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003581 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003582 if ((index < numArgs) &&
3583 (args[index] == String16("--list"))) {
3584 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003585 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003586 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003587 }
3588
3589 if ((index < numArgs) &&
3590 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003591 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003592 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003593 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003594 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003595
3596 if ((index < numArgs) &&
3597 (args[index] == String16("--latency-clear"))) {
3598 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003599 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003600 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003601 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003602
3603 if ((index < numArgs) &&
3604 (args[index] == String16("--dispsync"))) {
3605 index++;
3606 mPrimaryDispSync.dump(result);
3607 dumpAll = false;
3608 }
Dan Stozab90cf072015-03-05 11:05:59 -08003609
3610 if ((index < numArgs) &&
3611 (args[index] == String16("--static-screen"))) {
3612 index++;
3613 dumpStaticScreenStats(result);
3614 dumpAll = false;
3615 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003616
3617 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003618 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003619 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003620 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003621 dumpAll = false;
3622 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003623
3624 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3625 index++;
3626 dumpWideColorInfo(result);
3627 dumpAll = false;
3628 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003629 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003630
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003631 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003632 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003633 }
3634
Mathias Agopian9795c422009-08-26 16:36:26 -07003635 if (locked) {
3636 mStateLock.unlock();
3637 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003638 }
3639 write(fd, result.string(), result.size());
3640 return NO_ERROR;
3641}
3642
Dan Stozac7014012014-02-14 15:03:43 -08003643void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3644 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003645{
Robert Carr2047fae2016-11-28 14:09:09 -08003646 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003647 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003648 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003649}
3650
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003651void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003652 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003653{
3654 String8 name;
3655 if (index < args.size()) {
3656 name = String8(args[index]);
3657 index++;
3658 }
3659
Dan Stoza9e56aa02015-11-02 13:00:03 -08003660 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3661 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003662 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003663
3664 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003665 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003666 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003667 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003668 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003669 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003670 }
Robert Carr2047fae2016-11-28 14:09:09 -08003671 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003672 }
3673}
3674
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003675void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003676 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003677{
3678 String8 name;
3679 if (index < args.size()) {
3680 name = String8(args[index]);
3681 index++;
3682 }
3683
Robert Carr2047fae2016-11-28 14:09:09 -08003684 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003685 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003686 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003687 }
Robert Carr2047fae2016-11-28 14:09:09 -08003688 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003689
Svetoslavd85084b2014-03-20 10:28:31 -07003690 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003691}
3692
Jamie Gennis6547ff42013-07-16 20:12:42 -07003693// This should only be called from the main thread. Otherwise it would need
3694// the lock and should use mCurrentState rather than mDrawingState.
3695void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003696 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003697 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003698 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003699
3700 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3701}
3702
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003703void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003704{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003705 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003706 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3707
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003708 if (isLayerTripleBufferingDisabled())
3709 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003710
3711 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003712 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003713 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003714 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003715 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3716 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003717 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003718}
3719
Dan Stozab90cf072015-03-05 11:05:59 -08003720void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3721{
3722 result.appendFormat("Static screen stats:\n");
3723 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3724 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3725 float percent = 100.0f *
3726 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3727 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3728 b + 1, bucketTimeSec, percent);
3729 }
3730 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3731 float percent = 100.0f *
3732 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3733 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3734 NUM_BUCKETS - 1, bucketTimeSec, percent);
3735}
3736
Dan Stozae77c7662016-05-13 11:37:28 -07003737void SurfaceFlinger::recordBufferingStats(const char* layerName,
3738 std::vector<OccupancyTracker::Segment>&& history) {
3739 Mutex::Autolock lock(mBufferingStatsMutex);
3740 auto& stats = mBufferingStats[layerName];
3741 for (const auto& segment : history) {
3742 if (!segment.usedThirdBuffer) {
3743 stats.twoBufferTime += segment.totalTime;
3744 }
3745 if (segment.occupancyAverage < 1.0f) {
3746 stats.doubleBufferedTime += segment.totalTime;
3747 } else if (segment.occupancyAverage < 2.0f) {
3748 stats.tripleBufferedTime += segment.totalTime;
3749 }
3750 ++stats.numSegments;
3751 stats.totalTime += segment.totalTime;
3752 }
3753}
3754
Brian Andersond6927fb2016-07-23 23:37:30 -07003755void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3756 result.appendFormat("Layer frame timestamps:\n");
3757
3758 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3759 const size_t count = currentLayers.size();
3760 for (size_t i=0 ; i<count ; i++) {
3761 currentLayers[i]->dumpFrameEvents(result);
3762 }
3763}
3764
Dan Stozae77c7662016-05-13 11:37:28 -07003765void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3766 result.append("Buffering stats:\n");
3767 result.append(" [Layer name] <Active time> <Two buffer> "
3768 "<Double buffered> <Triple buffered>\n");
3769 Mutex::Autolock lock(mBufferingStatsMutex);
3770 typedef std::tuple<std::string, float, float, float> BufferTuple;
3771 std::map<float, BufferTuple, std::greater<float>> sorted;
3772 for (const auto& statsPair : mBufferingStats) {
3773 const char* name = statsPair.first.c_str();
3774 const BufferingStats& stats = statsPair.second;
3775 if (stats.numSegments == 0) {
3776 continue;
3777 }
3778 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3779 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3780 stats.totalTime;
3781 float doubleBufferRatio = static_cast<float>(
3782 stats.doubleBufferedTime) / stats.totalTime;
3783 float tripleBufferRatio = static_cast<float>(
3784 stats.tripleBufferedTime) / stats.totalTime;
3785 sorted.insert({activeTime, {name, twoBufferRatio,
3786 doubleBufferRatio, tripleBufferRatio}});
3787 }
3788 for (const auto& sortedPair : sorted) {
3789 float activeTime = sortedPair.first;
3790 const BufferTuple& values = sortedPair.second;
3791 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3792 std::get<0>(values).c_str(), activeTime,
3793 std::get<1>(values), std::get<2>(values),
3794 std::get<3>(values));
3795 }
3796 result.append("\n");
3797}
3798
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003799void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3800 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Romain Guy54f154a2017-10-24 21:40:32 +01003801 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003802
3803 // TODO: print out if wide-color mode is active or not
3804
3805 for (size_t d = 0; d < mDisplays.size(); d++) {
3806 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3807 int32_t hwcId = displayDevice->getHwcDisplayId();
3808 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3809 continue;
3810 }
3811
3812 result.appendFormat("Display %d color modes:\n", hwcId);
3813 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3814 for (auto&& mode : modes) {
3815 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3816 }
3817
3818 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3819 result.appendFormat(" Current color mode: %s (%d)\n",
3820 decodeColorMode(currentMode).c_str(), currentMode);
3821 }
3822 result.append("\n");
3823}
3824
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003825LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07003826 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003827 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
3828 const State& state = useDrawing ? mDrawingState : mCurrentState;
3829 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07003830 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003831 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07003832 });
3833
3834 return layersProto;
3835}
3836
Mathias Agopian74d211a2013-04-22 16:55:35 +02003837void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3838 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003839{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003840 bool colorize = false;
3841 if (index < args.size()
3842 && (args[index] == String16("--color"))) {
3843 colorize = true;
3844 index++;
3845 }
3846
3847 Colorizer colorizer(colorize);
3848
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003849 // figure out if we're stuck somewhere
3850 const nsecs_t now = systemTime();
3851 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3852 const nsecs_t inTransaction(mDebugInTransaction);
3853 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3854 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3855
3856 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003857 * Dump library configuration.
3858 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003859
3860 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003861 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003862 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003863 appendSfConfigString(result);
3864 appendUiConfigString(result);
3865 appendGuiConfigString(result);
3866 result.append("\n");
3867
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003868 result.append("\nWide-Color information:\n");
3869 dumpWideColorInfo(result);
3870
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003871 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003872 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003873 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003874 result.append(SyncFeatures::getInstance().toString());
3875 result.append("\n");
3876
Dan Stoza9e56aa02015-11-02 13:00:03 -08003877 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3878
Andy McFadden41d67d72014-04-25 16:58:34 -07003879 colorizer.bold(result);
3880 result.append("DispSync configuration: ");
3881 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003882 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003883 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003884 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003885 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003886 result.append("\n");
3887
Dan Stozab90cf072015-03-05 11:05:59 -08003888 // Dump static screen stats
3889 result.append("\n");
3890 dumpStaticScreenStats(result);
3891 result.append("\n");
3892
Dan Stozae77c7662016-05-13 11:37:28 -07003893 dumpBufferingStats(result);
3894
Andy McFadden4803b742012-09-24 19:07:20 -07003895 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003896 * Dump the visible layer list
3897 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003898 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003899 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003900 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07003901
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003902 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07003903 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
3904 result.append(LayerProtoParser::layersToString(layerTree).c_str());
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003905
3906 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003907 * Dump Display state
3908 */
3909
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003910 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003911 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003912 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003913 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3914 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003915 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003916 }
3917
3918 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003919 * Dump SurfaceFlinger global state
3920 */
3921
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003922 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003923 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003924 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003925
Mathias Agopian888c8222012-08-04 21:10:38 -07003926 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003927 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003928
Mathias Agopian875d8e12013-06-07 15:35:48 -07003929 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003930
Mathias Agopian42977342012-08-05 00:40:46 -07003931 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003932 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3933 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003934 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003935 " last eglSwapBuffers() time: %f us\n"
3936 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003937 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003938 " refresh-rate : %f fps\n"
3939 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003940 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003941 " gpu_to_cpu_unsupported : %d\n"
3942 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003943 mLastSwapBufferTime/1000.0,
3944 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003945 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003946 1e9 / activeConfig->getVsyncPeriod(),
3947 activeConfig->getDpiX(),
3948 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003949 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003950
Mathias Agopian74d211a2013-04-22 16:55:35 +02003951 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003952 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003953
Mathias Agopian74d211a2013-04-22 16:55:35 +02003954 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003955 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003956
3957 /*
3958 * VSYNC state
3959 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003960 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003961 result.append("\n");
3962
3963 /*
3964 * HWC layer minidump
3965 */
3966 for (size_t d = 0; d < mDisplays.size(); d++) {
3967 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3968 int32_t hwcId = displayDevice->getHwcDisplayId();
3969 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3970 continue;
3971 }
3972
3973 result.appendFormat("Display %d HWC layers:\n", hwcId);
3974 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003975 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003976 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003977 });
Dan Stozae22aec72016-08-01 13:20:59 -07003978 result.append("\n");
3979 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003980
3981 /*
3982 * Dump HWComposer state
3983 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003984 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003985 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003986 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003987 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003988 result.appendFormat(" h/w composer %s\n",
3989 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003990 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003991
3992 /*
3993 * Dump gralloc state
3994 */
3995 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3996 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07003997
3998 /*
3999 * Dump VrFlinger state if in use.
4000 */
4001 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4002 result.append("VrFlinger state:\n");
4003 result.append(mVrFlinger->Dump().c_str());
4004 result.append("\n");
4005 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004006}
4007
Mathias Agopian13127d82013-03-05 17:47:11 -08004008const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004009SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004010 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004011 wp<IBinder> dpy;
4012 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4013 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4014 dpy = mDisplays.keyAt(i);
4015 break;
4016 }
4017 }
4018 if (dpy == NULL) {
4019 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4020 // Just use the primary display so we have something to return
4021 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4022 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004023 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004024}
4025
Keun young Park63f165f2012-08-31 10:53:36 -07004026bool SurfaceFlinger::startDdmConnection()
4027{
4028 void* libddmconnection_dso =
4029 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4030 if (!libddmconnection_dso) {
4031 return false;
4032 }
4033 void (*DdmConnection_start)(const char* name);
4034 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004035 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004036 if (!DdmConnection_start) {
4037 dlclose(libddmconnection_dso);
4038 return false;
4039 }
4040 (*DdmConnection_start)(getServiceName());
4041 return true;
4042}
4043
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004044status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004045 switch (code) {
4046 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004047 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004048 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004049 case CLEAR_ANIMATION_FRAME_STATS:
4050 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004051 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004052 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004053 case ENABLE_VSYNC_INJECTIONS:
4054 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004055 {
4056 // codes that require permission check
4057 IPCThreadState* ipc = IPCThreadState::self();
4058 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004059 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004060 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004061 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004062 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004063 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004064 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004065 break;
4066 }
Robert Carr1db73f62016-12-21 12:58:51 -08004067 /*
4068 * Calling setTransactionState is safe, because you need to have been
4069 * granted a reference to Client* and Handle* to do anything with it.
4070 *
4071 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4072 */
4073 case SET_TRANSACTION_STATE:
4074 case CREATE_SCOPED_CONNECTION:
4075 {
4076 return OK;
4077 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004078 case CAPTURE_SCREEN:
4079 {
4080 // codes that require permission check
4081 IPCThreadState* ipc = IPCThreadState::self();
4082 const int pid = ipc->getCallingPid();
4083 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004084 if ((uid != AID_GRAPHICS) &&
4085 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004086 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004087 return PERMISSION_DENIED;
4088 }
4089 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004090 }
chaviwa76b2712017-09-20 12:02:26 -07004091 case CAPTURE_LAYERS: {
4092 IPCThreadState* ipc = IPCThreadState::self();
4093 const int pid = ipc->getCallingPid();
4094 const int uid = ipc->getCallingUid();
4095 if ((uid != AID_GRAPHICS) &&
4096 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4097 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4098 return PERMISSION_DENIED;
4099 }
4100 break;
4101 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004102 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004103 return OK;
4104}
4105
4106status_t SurfaceFlinger::onTransact(
4107 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4108{
4109 status_t credentialCheck = CheckTransactCodeCredentials(code);
4110 if (credentialCheck != OK) {
4111 return credentialCheck;
4112 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004113
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004114 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4115 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004116 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004117 IPCThreadState* ipc = IPCThreadState::self();
4118 const int uid = ipc->getCallingUid();
4119 if (CC_UNLIKELY(uid != AID_SYSTEM
4120 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004121 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004122 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004123 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004124 return PERMISSION_DENIED;
4125 }
4126 int n;
4127 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004128 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004129 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004130 return NO_ERROR;
4131 case 1002: // SHOW_UPDATES
4132 n = data.readInt32();
4133 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004134 invalidateHwcGeometry();
4135 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004136 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004137 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004138 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004139 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004140 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004141 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004142 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004143 setTransactionFlags(
4144 eTransactionNeeded|
4145 eDisplayTransactionNeeded|
4146 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004147 return NO_ERROR;
4148 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004149 case 1006:{ // send empty update
4150 signalRefresh();
4151 return NO_ERROR;
4152 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004153 case 1008: // toggle use of hw composer
4154 n = data.readInt32();
4155 mDebugDisableHWC = n ? 1 : 0;
4156 invalidateHwcGeometry();
4157 repaintEverything();
4158 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004159 case 1009: // toggle use of transform hint
4160 n = data.readInt32();
4161 mDebugDisableTransformHint = n ? 1 : 0;
4162 invalidateHwcGeometry();
4163 repaintEverything();
4164 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004165 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004166 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004167 reply->writeInt32(0);
4168 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004169 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004170 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004171 return NO_ERROR;
4172 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004173 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004174 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004175 return NO_ERROR;
4176 }
4177 case 1014: {
4178 // daltonize
4179 n = data.readInt32();
4180 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004181 case 1:
4182 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4183 break;
4184 case 2:
4185 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4186 break;
4187 case 3:
4188 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4189 break;
4190 default:
4191 mDaltonizer.setType(ColorBlindnessType::None);
4192 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004193 }
4194 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004195 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004196 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004197 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004198 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004199 invalidateHwcGeometry();
4200 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004201 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004202 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004203 case 1015: {
4204 // apply a color matrix
4205 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004206 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004207 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004208 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004209 for (size_t j = 0; j < 4; j++) {
4210 mColorMatrix[i][j] = data.readFloat();
4211 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004212 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004213 } else {
4214 mColorMatrix = mat4();
4215 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004216
4217 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4218 // the division by w in the fragment shader
4219 float4 lastRow(transpose(mColorMatrix)[3]);
4220 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4221 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4222 }
4223
Alan Viverette9c5a3332013-09-12 20:04:35 -07004224 invalidateHwcGeometry();
4225 repaintEverything();
4226 return NO_ERROR;
4227 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004228 // This is an experimental interface
4229 // Needs to be shifted to proper binder interface when we productize
4230 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004231 n = data.readInt32();
4232 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004233 return NO_ERROR;
4234 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004235 case 1017: {
4236 n = data.readInt32();
4237 mForceFullDamage = static_cast<bool>(n);
4238 return NO_ERROR;
4239 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004240 case 1018: { // Modify Choreographer's phase offset
4241 n = data.readInt32();
4242 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4243 return NO_ERROR;
4244 }
4245 case 1019: { // Modify SurfaceFlinger's phase offset
4246 n = data.readInt32();
4247 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4248 return NO_ERROR;
4249 }
Irvel468051e2016-06-13 16:44:44 -07004250 case 1020: { // Layer updates interceptor
4251 n = data.readInt32();
4252 if (n) {
4253 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004254 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004255 }
4256 else{
4257 ALOGV("Interceptor disabled");
4258 mInterceptor.disable();
4259 }
4260 return NO_ERROR;
4261 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004262 case 1021: { // Disable HWC virtual displays
4263 n = data.readInt32();
4264 mUseHwcVirtualDisplays = !n;
4265 return NO_ERROR;
4266 }
Romain Guy0147a172017-06-01 13:53:56 -07004267 case 1022: { // Set saturation boost
4268 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4269
4270 invalidateHwcGeometry();
4271 repaintEverything();
4272 return NO_ERROR;
4273 }
Romain Guy54f154a2017-10-24 21:40:32 +01004274 case 1023: { // Set native mode
4275 mForceNativeColorMode = data.readInt32() == 1;
4276
4277 invalidateHwcGeometry();
4278 repaintEverything();
4279 return NO_ERROR;
4280 }
4281 case 1024: { // Is wide color gamut rendering/color management supported?
4282 reply->writeBool(hasWideColorDisplay);
4283 return NO_ERROR;
4284 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01004285 case 1025: { // tracing
4286 n = data.readInt32();
4287 if (n) {
4288 ALOGV("LayerTracing enabled");
4289 mTracing.enable();
4290 doTracing("tracing.enable");
4291 reply->writeInt32(NO_ERROR);
4292 } else {
4293 ALOGV("LayerTracing disabled");
4294 status_t err = mTracing.disable();
4295 reply->writeInt32(err);
4296 }
4297 return NO_ERROR;
4298 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004299 }
4300 }
4301 return err;
4302}
4303
Steven Thomas6d8110b2017-08-31 18:24:21 -07004304void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004305 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004306 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004307}
4308
Steven Thomas6d8110b2017-08-31 18:24:21 -07004309void SurfaceFlinger::repaintEverything() {
4310 ConditionalLock _l(mStateLock,
4311 std::this_thread::get_id() != mMainThreadId);
4312 repaintEverythingLocked();
4313}
4314
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004315// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4316class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004317public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004318 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4319 ~WindowDisconnector() {
4320 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004321 }
4322
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004323private:
4324 ANativeWindow* mWindow;
4325 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004326};
4327
chaviwa252d892017-11-20 17:54:25 -08004328status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4329 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4330 int32_t minLayerZ, int32_t maxLayerZ,
4331 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004332 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004333 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004334
chaviwa76b2712017-09-20 12:02:26 -07004335 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4336
4337 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4338 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4339
4340 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4341 device, minLayerZ, maxLayerZ, std::placeholders::_1);
chaviwa252d892017-11-20 17:54:25 -08004342 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004343}
4344
4345status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
chaviwa252d892017-11-20 17:54:25 -08004346 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
4347 float frameScale) {
chaviwa76b2712017-09-20 12:02:26 -07004348 ATRACE_CALL();
4349
4350 class LayerRenderArea : public RenderArea {
4351 public:
chaviw7206d492017-11-10 16:16:12 -08004352 LayerRenderArea(const sp<Layer>& layer, const Rect crop, int32_t reqWidth,
chaviwa252d892017-11-20 17:54:25 -08004353 int32_t reqHeight)
chaviw7206d492017-11-10 16:16:12 -08004354 : RenderArea(reqHeight, reqWidth), mLayer(layer), mCrop(crop) {}
chaviwa76b2712017-09-20 12:02:26 -07004355 const Transform& getTransform() const override {
4356 // Make the top level transform the inverse the transform and it's parent so it sets
4357 // the whole capture back to 0,0
4358 return *new Transform(mLayer->getTransform().inverse());
4359 }
4360 Rect getBounds() const override {
4361 const Layer::State& layerState(mLayer->getDrawingState());
4362 return Rect(layerState.active.w, layerState.active.h);
4363 }
4364 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4365 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4366 bool isSecure() const override { return false; }
4367 bool needsFiltering() const override { return false; }
4368
chaviw7206d492017-11-10 16:16:12 -08004369 Rect getSourceCrop() const override {
4370 if (mCrop.isEmpty()) {
4371 return getBounds();
4372 } else {
4373 return mCrop;
4374 }
4375 }
chaviwa76b2712017-09-20 12:02:26 -07004376 bool getWideColorSupport() const override { return false; }
4377 android_color_mode_t getActiveColorMode() const override { return HAL_COLOR_MODE_NATIVE; }
4378
4379 private:
chaviw7206d492017-11-10 16:16:12 -08004380 const sp<Layer> mLayer;
4381 const Rect mCrop;
chaviwa76b2712017-09-20 12:02:26 -07004382 };
4383
4384 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4385 auto parent = layerHandle->owner.promote();
4386
chaviw7206d492017-11-10 16:16:12 -08004387 if (parent == nullptr || parent->isPendingRemoval()) {
4388 ALOGE("captureLayers called with a removed parent");
4389 return NAME_NOT_FOUND;
4390 }
4391
4392 Rect crop(sourceCrop);
4393 if (sourceCrop.width() <= 0) {
4394 crop.left = 0;
4395 crop.right = parent->getCurrentState().active.w;
4396 }
4397
4398 if (sourceCrop.height() <= 0) {
4399 crop.top = 0;
4400 crop.bottom = parent->getCurrentState().active.h;
4401 }
4402
4403 int32_t reqWidth = crop.width() * frameScale;
4404 int32_t reqHeight = crop.height() * frameScale;
4405
4406 LayerRenderArea renderArea(parent, crop, reqWidth, reqHeight);
4407
chaviwa76b2712017-09-20 12:02:26 -07004408 auto traverseLayers = [parent](const LayerVector::Visitor& visitor) {
4409 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4410 if (!layer->isVisible()) {
4411 return;
4412 }
4413 visitor(layer);
4414 });
4415 };
chaviwa252d892017-11-20 17:54:25 -08004416 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004417}
4418
4419status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4420 TraverseLayersFunction traverseLayers,
chaviwa252d892017-11-20 17:54:25 -08004421 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004422 bool useIdentityTransform) {
4423 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004424
chaviwa76b2712017-09-20 12:02:26 -07004425 renderArea.updateDimensions();
4426
chaviwa252d892017-11-20 17:54:25 -08004427 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4428 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4429 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4430 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004431
4432 // This mutex protects syncFd and captureResult for communication of the return values from the
4433 // main thread back to this Binder thread
4434 std::mutex captureMutex;
4435 std::condition_variable captureCondition;
4436 std::unique_lock<std::mutex> captureLock(captureMutex);
4437 int syncFd = -1;
4438 std::optional<status_t> captureResult;
4439
4440 sp<LambdaMessage> message = new LambdaMessage([&]() {
4441 // If there is a refresh pending, bug out early and tell the binder thread to try again
4442 // after the refresh.
4443 if (mRefreshPending) {
4444 ATRACE_NAME("Skipping screenshot for now");
4445 std::unique_lock<std::mutex> captureLock(captureMutex);
4446 captureResult = std::make_optional<status_t>(EAGAIN);
4447 captureCondition.notify_one();
4448 return;
4449 }
4450
4451 status_t result = NO_ERROR;
4452 int fd = -1;
4453 {
4454 Mutex::Autolock _l(mStateLock);
chaviwa252d892017-11-20 17:54:25 -08004455 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4456 useIdentityTransform, &fd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004457 }
4458
4459 {
4460 std::unique_lock<std::mutex> captureLock(captureMutex);
4461 syncFd = fd;
4462 captureResult = std::make_optional<status_t>(result);
4463 captureCondition.notify_one();
4464 }
4465 });
4466
chaviwa252d892017-11-20 17:54:25 -08004467 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004468 if (result == NO_ERROR) {
4469 captureCondition.wait(captureLock, [&]() { return captureResult; });
4470 while (*captureResult == EAGAIN) {
4471 captureResult.reset();
4472 result = postMessageAsync(message);
4473 if (result != NO_ERROR) {
4474 return result;
4475 }
4476 captureCondition.wait(captureLock, [&]() { return captureResult; });
4477 }
4478 result = *captureResult;
4479 }
4480
4481 if (result == NO_ERROR) {
chaviwa252d892017-11-20 17:54:25 -08004482 sync_wait(syncFd, -1);
4483 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004484 }
chaviwa252d892017-11-20 17:54:25 -08004485
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004486 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004487}
4488
chaviwa76b2712017-09-20 12:02:26 -07004489void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4490 TraverseLayersFunction traverseLayers, bool yswap,
4491 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004492 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004493
Mathias Agopian3f844832013-08-07 21:24:32 -07004494 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004495
4496 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004497 const auto raWidth = renderArea.getWidth();
4498 const auto raHeight = renderArea.getHeight();
4499
4500 const auto reqWidth = renderArea.getReqWidth();
4501 const auto reqHeight = renderArea.getReqHeight();
4502 Rect sourceCrop = renderArea.getSourceCrop();
4503
4504 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4505 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004506
Dan Stozac1879002014-05-22 15:59:05 -07004507 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004508 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004509 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004510 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004511 }
4512
4513 // ensure that sourceCrop is inside screen
4514 if (sourceCrop.left < 0) {
4515 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4516 }
chaviwa76b2712017-09-20 12:02:26 -07004517 if (sourceCrop.right > raWidth) {
4518 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004519 }
4520 if (sourceCrop.top < 0) {
4521 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4522 }
chaviwa76b2712017-09-20 12:02:26 -07004523 if (sourceCrop.bottom > raHeight) {
4524 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004525 }
4526
chaviwa76b2712017-09-20 12:02:26 -07004527 engine.setWideColor(renderArea.getWideColorSupport() && !mForceNativeColorMode);
chaviwa252d892017-11-20 17:54:25 -08004528 engine.setColorMode(mForceNativeColorMode ? HAL_COLOR_MODE_NATIVE
4529 : renderArea.getActiveColorMode());
Romain Guy88d37dd2017-05-26 17:57:05 -07004530
Mathias Agopian180f10d2013-04-10 22:55:41 -07004531 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004532 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004533
4534 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004535 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4536 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004537 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004538
4539 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004540 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004541
chaviwa76b2712017-09-20 12:02:26 -07004542 traverseLayers([&](Layer* layer) {
4543 if (filtering) layer->setFiltering(true);
4544 layer->draw(renderArea, useIdentityTransform);
4545 if (filtering) layer->setFiltering(false);
4546 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004547}
4548
Dan Stozaabcda352017-06-01 14:37:39 -07004549// A simple RAII class that holds an EGLImage and destroys it either:
4550// a) When the destroy() method is called
4551// b) When the object goes out of scope
4552class ImageHolder {
4553public:
4554 ImageHolder(EGLDisplay display, EGLImageKHR image) : mDisplay(display), mImage(image) {}
4555 ~ImageHolder() { destroy(); }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004556
Dan Stozaabcda352017-06-01 14:37:39 -07004557 void destroy() {
4558 if (mImage != EGL_NO_IMAGE_KHR) {
4559 eglDestroyImageKHR(mDisplay, mImage);
4560 mImage = EGL_NO_IMAGE_KHR;
4561 }
4562 }
4563
4564private:
4565 const EGLDisplay mDisplay;
4566 EGLImageKHR mImage;
4567};
4568
chaviwa76b2712017-09-20 12:02:26 -07004569status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4570 TraverseLayersFunction traverseLayers,
4571 ANativeWindowBuffer* buffer,
chaviwa252d892017-11-20 17:54:25 -08004572 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004573 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004574 ATRACE_CALL();
4575
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004576 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004577
4578 traverseLayers([&](Layer* layer) {
4579 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4580 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004581
chaviwa252d892017-11-20 17:54:25 -08004582 if (secureLayerIsVisible) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004583 ALOGW("FB is protected: PERMISSION_DENIED");
4584 return PERMISSION_DENIED;
4585 }
4586
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004587 // create an EGLImage from the buffer so we can later
4588 // turn it into a texture
4589 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4590 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4591 if (image == EGL_NO_IMAGE_KHR) {
4592 return BAD_VALUE;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004593 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004594
Dan Stozaabcda352017-06-01 14:37:39 -07004595 // This will automatically destroy the image if we return before calling its destroy method
4596 ImageHolder imageHolder(mEGLDisplay, image);
4597
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004598 // this binds the given EGLImage as a framebuffer for the
4599 // duration of this scope.
4600 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
Dan Stozaabcda352017-06-01 14:37:39 -07004601 if (imageBond.getStatus() != NO_ERROR) {
4602 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004603 return INVALID_OPERATION;
4604 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004605
Dan Stozaabcda352017-06-01 14:37:39 -07004606 // this will in fact render into our dequeued buffer
4607 // via an FBO, which means we didn't have to create
4608 // an EGLSurface and therefore we're not
4609 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004610 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004611
Chia-I Wub0c041b2017-11-09 11:36:33 -08004612 *outSyncFd = getRenderEngine().flush(DEBUG_SCREENSHOTS);
Dan Stozaabcda352017-06-01 14:37:39 -07004613
4614 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004615 const auto reqWidth = renderArea.getReqWidth();
4616 const auto reqHeight = renderArea.getReqHeight();
4617
Dan Stozaabcda352017-06-01 14:37:39 -07004618 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4619 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004620 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004621 delete [] pixels;
4622 }
4623
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004624 // destroy our image
Dan Stozaabcda352017-06-01 14:37:39 -07004625 imageHolder.destroy();
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004626 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004627}
4628
Mathias Agopiand5556842013-09-19 17:08:37 -07004629void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07004630 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004631 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004632 for (size_t y = 0; y < h; y++) {
4633 uint32_t const* p = (uint32_t const*)vaddr + y * s;
4634 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004635 if (p[x] != 0xFF000000) return;
4636 }
4637 }
chaviwa76b2712017-09-20 12:02:26 -07004638 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07004639
Robert Carr2047fae2016-11-28 14:09:09 -08004640 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07004641 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004642 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07004643 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4644 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
4645 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
4646 static_cast<float>(state.color.a));
4647 i++;
4648 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07004649 }
4650}
4651
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004652// ---------------------------------------------------------------------------
4653
Dan Stoza412903f2017-04-27 13:42:17 -07004654void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4655 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004656}
4657
Dan Stoza412903f2017-04-27 13:42:17 -07004658void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4659 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004660}
4661
chaviwa76b2712017-09-20 12:02:26 -07004662void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
4663 int32_t maxLayerZ,
4664 const LayerVector::Visitor& visitor) {
4665 // We loop through the first level of layers without traversing,
4666 // as we need to interpret min/max layer Z in the top level Z space.
4667 for (const auto& layer : mDrawingState.layersSortedByZ) {
4668 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4669 continue;
4670 }
4671 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08004672 // relative layers are traversed in Layer::traverseInZOrder
4673 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07004674 continue;
4675 }
4676 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4677 if (!layer->isVisible()) {
4678 return;
4679 }
4680 visitor(layer);
4681 });
4682 }
4683}
4684
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004685}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004686
4687
4688#if defined(__gl_h_)
4689#error "don't include gl/gl.h in this file"
4690#endif
4691
4692#if defined(__gl2_h_)
4693#error "don't include gl2/gl2.h in this file"
chaviwa252d892017-11-20 17:54:25 -08004694#endif