blob: a21b7eaeeeb4c7ea6e41faed1d9af7499e2c4d47 [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
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060040#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070041#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070042#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043
Jamie Gennis1a4d8832012-08-02 20:11:05 -070044#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070045#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080047#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080048#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070049
50#include <ui/GraphicBufferAllocator.h>
51#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080053
Mathias Agopiancde87a32012-09-13 14:09:01 -070054#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080055#include <utils/String8.h>
56#include <utils/String16.h>
57#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070058#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080059#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060
Mathias Agopian921e6ac2012-07-23 23:11:29 -070061#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070062#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063
Robert Carr578038f2018-03-09 12:25:24 -080064#include "BufferLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020065#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080066#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020067#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080068#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080069#include "DdmConnection.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070070#include "DispSync.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "DisplayDevice.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070072#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080073#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
Robert Carr578038f2018-03-09 12:25:24 -080078#include "clz.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Steven Thomasb02664d2017-07-26 18:48:28 -070080#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070081#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070082#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070083#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084
Mathias Agopianff2ed702013-09-01 21:36:12 -070085#include "Effects/Daltonizer.h"
86
Mathias Agopian875d8e12013-06-07 15:35:48 -070087#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070088#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070089
Jiyong Park4b20c2e2017-01-14 19:45:11 +090090#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090091#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090092
chaviw1d044282017-09-27 12:19:28 -070093#include <layerproto/LayerProtoParser.h>
94
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080095#define DISPLAY_COUNT 1
96
Mathias Agopianfee2b462013-07-03 12:34:01 -070097/*
98 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
99 * black pixels.
100 */
101#define DEBUG_SCREENSHOTS false
102
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800103namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700104
Jaesoo Lee43518572017-01-23 19:03:16 +0900105using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900106using namespace android::hardware::configstore::V1_0;
107
Steven Thomasb02664d2017-07-26 18:48:28 -0700108namespace {
109class ConditionalLock {
110public:
111 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
112 if (lock) {
113 mMutex.lock();
114 }
115 }
116 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
117private:
118 Mutex& mMutex;
119 bool mLocked;
120};
121} // namespace anonymous
122
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800123// ---------------------------------------------------------------------------
124
Mathias Agopian99b49842011-06-27 16:05:52 -0700125const String16 sHardwareTest("android.permission.HARDWARE_TEST");
126const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
127const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
128const String16 sDump("android.permission.DUMP");
129
130// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800131int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
132int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700133int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700134bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800135uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800136bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800137bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800138int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800139// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600140bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700141
Kalle Raitaa099a242017-01-11 11:17:29 -0800142
143std::string getHwcServiceName() {
144 char value[PROPERTY_VALUE_MAX] = {};
145 property_get("debug.sf.hwc_service_name", value, "default");
146 ALOGI("Using HWComposer service: '%s'", value);
147 return std::string(value);
148}
149
150bool useTrebleTestingOverride() {
151 char value[PROPERTY_VALUE_MAX] = {};
152 property_get("debug.sf.treble_testing_override", value, "false");
153 ALOGI("Treble testing override: '%s'", value);
154 return std::string(value) == "true";
155}
156
Lloyd Pique99d3da52018-01-22 17:48:03 -0800157NativeWindowSurface::~NativeWindowSurface() = default;
158
159namespace impl {
160
161class NativeWindowSurface final : public android::NativeWindowSurface {
162public:
163 static std::unique_ptr<android::NativeWindowSurface> create(
164 const sp<IGraphicBufferProducer>& producer) {
165 return std::make_unique<NativeWindowSurface>(producer);
166 }
167
168 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
169 : surface(new Surface(producer, false)) {}
170
171 ~NativeWindowSurface() override = default;
172
173private:
174 sp<ANativeWindow> getNativeWindow() const override { return surface; }
175
176 void preallocateBuffers() override { surface->allocateBuffers(); }
177
178 sp<Surface> surface;
179};
180
181} // namespace impl
182
David Sodmanbc815282017-11-05 18:57:52 -0800183SurfaceFlingerBE::SurfaceFlingerBE()
184 : mHwcServiceName(getHwcServiceName()),
185 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800186 mFrameBuckets(),
187 mTotalTime(0),
188 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800189 mComposerSequenceId(0) {
190}
191
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800192SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800193 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800194 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700195 mTransactionPending(false),
196 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700197 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700198 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700199 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800200 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800201 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800202 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800203 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800204 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800205 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700206 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700207 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700208 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700209 mDebugInSwapBuffers(0),
210 mLastSwapBufferTime(0),
211 mDebugInTransaction(0),
212 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700213 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700214 mForceFullDamage(false),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000215 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700216 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700217 mHWVsyncAvailable(false),
Romain Guya9638732017-06-01 12:05:21 -0700218 mHasColorMatrix(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800219 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800220 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700221 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800222 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800223 mCreateBufferQueue(&BufferQueue::createBufferQueue),
224 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800225
226SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800227 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800228
229 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
230 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
231
232 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
233 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
234
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800235 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
236 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800237
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700238 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
239 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
240
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700241 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
242 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
243
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800244 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
245 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
246
Steven Thomas050b2c82017-03-06 11:45:16 -0800247 // Vr flinger is only enabled on Daydream ready devices.
248 useVrFlinger = getBool< ISurfaceFlingerConfigs,
249 &ISurfaceFlingerConfigs::useVrFlinger>(false);
250
Fabien Sanglard1971b632017-03-10 14:50:03 -0800251 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
252 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
253
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600254 hasWideColorDisplay =
255 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
256
David Sodman99974d22017-11-28 12:04:33 -0800257 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700258
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800259 // debugging stuff...
260 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700261
Mathias Agopianb4b17302013-03-20 18:36:41 -0700262 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700263 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700264
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800265 property_get("debug.sf.showupdates", value, "0");
266 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700267
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700268 property_get("debug.sf.ddms", value, "0");
269 mDebugDDMS = atoi(value);
270 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700271 if (!startDdmConnection()) {
272 // start failed, and DDMS debugging not enabled
273 mDebugDDMS = 0;
274 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700275 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700276 ALOGI_IF(mDebugRegion, "showupdates enabled");
277 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700278
279 property_get("debug.sf.disable_backpressure", value, "0");
280 mPropagateBackpressure = !atoi(value);
281 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700282
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800283 property_get("debug.sf.enable_hwc_vds", value, "0");
284 mUseHwcVirtualDisplays = atoi(value);
285 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800286
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800287 property_get("ro.sf.disable_triple_buffer", value, "1");
288 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800289 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700290
Dan Stoza0a0158c2018-03-16 13:38:54 -0700291 // TODO (b/74616334): Reduce the default value once we isolate the leak
292 const size_t defaultListSize = 4 * MAX_LAYERS;
293 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
294 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
295
Romain Guy11d63f42017-07-20 12:47:14 -0700296 // We should be reading 'persist.sys.sf.color_saturation' here
297 // but since /data may be encrypted, we need to wait until after vold
298 // comes online to attempt to read the property. The property is
299 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800300
301 if (useTrebleTestingOverride()) {
302 // Without the override SurfaceFlinger cannot connect to HIDL
303 // services that are not listed in the manifests. Considered
304 // deriving the setting from the set service name, but it
305 // would be brittle if the name that's not 'default' is used
306 // for production purposes later on.
307 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
308 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800309}
310
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800311void SurfaceFlinger::onFirstRef()
312{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800313 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800314}
315
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800316SurfaceFlinger::~SurfaceFlinger()
317{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800318}
319
Dan Stozac7014012014-02-14 15:03:43 -0800320void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800321{
322 // the window manager died on us. prepare its eulogy.
323
Andy McFadden13a082e2012-08-24 10:16:42 -0700324 // restore initial conditions (default device unblank, etc)
325 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800326
327 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700328 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800329}
330
Robert Carr1db73f62016-12-21 12:58:51 -0800331static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700332 status_t err = client->initCheck();
333 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800334 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800335 }
Robert Carr1db73f62016-12-21 12:58:51 -0800336 return nullptr;
337}
338
339sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
340 return initClient(new Client(this));
341}
342
343sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
344 const sp<IGraphicBufferProducer>& gbp) {
345 if (authenticateSurfaceTexture(gbp) == false) {
346 return nullptr;
347 }
348 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
349 if (layer == nullptr) {
350 return nullptr;
351 }
352
353 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800354}
355
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700356sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
357 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700358{
359 class DisplayToken : public BBinder {
360 sp<SurfaceFlinger> flinger;
361 virtual ~DisplayToken() {
362 // no more references, this display must be terminated
363 Mutex::Autolock _l(flinger->mStateLock);
364 flinger->mCurrentState.displays.removeItem(this);
365 flinger->setTransactionFlags(eDisplayTransactionNeeded);
366 }
367 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700368 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700369 : flinger(flinger) {
370 }
371 };
372
373 sp<BBinder> token = new DisplayToken(this);
374
375 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700376 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700377 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700378 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800379 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700380 return token;
381}
382
Jesse Hall6c913be2013-08-08 12:15:49 -0700383void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
384 Mutex::Autolock _l(mStateLock);
385
386 ssize_t idx = mCurrentState.displays.indexOfKey(display);
387 if (idx < 0) {
388 ALOGW("destroyDisplay: invalid display token");
389 return;
390 }
391
392 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
393 if (!info.isVirtualDisplay()) {
394 ALOGE("destroyDisplay called for non-virtual display");
395 return;
396 }
Lloyd Pique4dccc412018-01-22 17:21:36 -0800397 mInterceptor->saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700398 mCurrentState.displays.removeItemsAt(idx);
399 setTransactionFlags(eDisplayTransactionNeeded);
400}
401
Mathias Agopiane57f2922012-08-09 16:29:12 -0700402sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700403 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700404 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800405 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700406 }
Jesse Hall692c7232012-11-08 15:41:56 -0800407 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700408}
409
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800410void SurfaceFlinger::bootFinished()
411{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700412 if (mStartPropertySetThread->join() != NO_ERROR) {
413 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800414 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800415 const nsecs_t now = systemTime();
416 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000417 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700418
419 // wait patiently for the window manager death
420 const String16 name("window");
421 sp<IBinder> window(defaultServiceManager()->getService(name));
422 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700423 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700424 }
425
Steven Thomas050b2c82017-03-06 11:45:16 -0800426 if (mVrFlinger) {
427 mVrFlinger->OnBootFinished();
428 }
429
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700430 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700431 // formerly we would just kill the process, but we now ask it to exit so it
432 // can choose where to stop the animation.
433 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700434
435 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
436 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
437 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700438
Thierry Strudel2924d012017-08-14 15:19:37 -0700439 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700440 readPersistentProperties();
441 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700442 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800443}
444
Mathias Agopian3f844832013-08-07 21:24:32 -0700445void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700446 class MessageDestroyGLTexture : public MessageBase {
Lloyd Pique144e1162017-12-20 16:44:52 -0800447 RE::RenderEngine& engine;
Mathias Agopian3f844832013-08-07 21:24:32 -0700448 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700449 public:
Lloyd Pique144e1162017-12-20 16:44:52 -0800450 MessageDestroyGLTexture(RE::RenderEngine& engine, uint32_t texture)
451 : engine(engine), texture(texture) {}
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700452 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700453 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700454 return true;
455 }
456 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700457 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700458}
459
Lloyd Piquee83f9312018-02-01 12:53:17 -0800460class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700461public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700462 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000463 const char* name) :
464 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700465 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700466 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000467 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
468 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700469 mDispSync(dispSync),
470 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700471 mVsyncMutex(),
472 mPhaseOffset(phaseOffset),
473 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700474
Lloyd Piquee83f9312018-02-01 12:53:17 -0800475 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700476
Lloyd Piquee83f9312018-02-01 12:53:17 -0800477 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700478 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700479 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000480 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700481 static_cast<DispSync::Callback*>(this));
482 if (err != NO_ERROR) {
483 ALOGE("error registering vsync callback: %s (%d)",
484 strerror(-err), err);
485 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700486 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700487 } else {
488 status_t err = mDispSync->removeEventListener(
489 static_cast<DispSync::Callback*>(this));
490 if (err != NO_ERROR) {
491 ALOGE("error unregistering vsync callback: %s (%d)",
492 strerror(-err), err);
493 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700494 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700495 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700496 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700497 }
498
Lloyd Piquee83f9312018-02-01 12:53:17 -0800499 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700500 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700501 mCallback = callback;
502 }
503
Lloyd Piquee83f9312018-02-01 12:53:17 -0800504 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700505 Mutex::Autolock lock(mVsyncMutex);
506
507 // Normalize phaseOffset to [0, period)
508 auto period = mDispSync->getPeriod();
509 phaseOffset %= period;
510 if (phaseOffset < 0) {
511 // If we're here, then phaseOffset is in (-period, 0). After this
512 // operation, it will be in (0, period)
513 phaseOffset += period;
514 }
515 mPhaseOffset = phaseOffset;
516
517 // If we're not enabled, we don't need to mess with the listeners
518 if (!mEnabled) {
519 return;
520 }
521
522 // Remove the listener with the old offset
523 status_t err = mDispSync->removeEventListener(
524 static_cast<DispSync::Callback*>(this));
525 if (err != NO_ERROR) {
526 ALOGE("error unregistering vsync callback: %s (%d)",
527 strerror(-err), err);
528 }
529
530 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000531 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700532 static_cast<DispSync::Callback*>(this));
533 if (err != NO_ERROR) {
534 ALOGE("error registering vsync callback: %s (%d)",
535 strerror(-err), err);
536 }
537 }
538
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700539private:
540 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800541 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700542 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700543 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700544 callback = mCallback;
545
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700546 if (mTraceVsync) {
547 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700548 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700549 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700550 }
551
Peiyong Lin566a3b42018-01-09 18:22:43 -0800552 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700553 callback->onVSyncEvent(when);
554 }
555 }
556
Tim Murray4a4e4a22016-04-19 16:29:23 +0000557 const char* const mName;
558
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700559 int mValue;
560
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700561 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700562 const String8 mVsyncOnLabel;
563 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700564
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700565 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700566
567 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800568 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700569
570 Mutex mVsyncMutex; // Protects the following
571 nsecs_t mPhaseOffset;
572 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700573};
574
Lloyd Piquee83f9312018-02-01 12:53:17 -0800575class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700576public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800577 InjectVSyncSource() = default;
578 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700579
Lloyd Piquee83f9312018-02-01 12:53:17 -0800580 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700581 std::lock_guard<std::mutex> lock(mCallbackMutex);
582 mCallback = callback;
583 }
584
Lloyd Piquee83f9312018-02-01 12:53:17 -0800585 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700586 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700587 if (mCallback) {
588 mCallback->onVSyncEvent(when);
589 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700590 }
591
Lloyd Piquee83f9312018-02-01 12:53:17 -0800592 void setVSyncEnabled(bool) override {}
593 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700594
595private:
596 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800597 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700598};
599
Wei Wangf9b05ee2017-07-19 20:59:39 -0700600// Do not call property_set on main thread which will be blocked by init
601// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700602void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700603 ALOGI( "SurfaceFlinger's main thread ready to run. "
604 "Initializing graphics H/W...");
605
Thierry Strudel2924d012017-08-14 15:19:37 -0700606 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900607
Steven Thomasb02664d2017-07-26 18:48:28 -0700608 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800609
Steven Thomasb02664d2017-07-26 18:48:28 -0700610 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800611 mEventThreadSource =
612 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
613 true, "app");
614 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(), *this, false,
615 "appEventThread");
616 mSfEventThreadSource =
617 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
618 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800619
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800620 mSFEventThread = std::make_unique<impl::EventThread>(mSfEventThreadSource.get(), *this, true,
621 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800622 mEventQueue->setEventThread(mSFEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800623
Steven Thomasb02664d2017-07-26 18:48:28 -0700624 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800625 getBE().mRenderEngine =
626 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
627 hasWideColorDisplay
628 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
629 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800630 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700631
632 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
633 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800634 getBE().mHwc.reset(
635 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700636 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800637 // Process any initial hotplug and resulting display changes.
638 processDisplayHotplugEventsLocked();
639 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
640 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800641
Lloyd Piquefcd86612017-12-14 17:15:36 -0800642 // make the default display GLContext current so that we can create textures
643 // when creating Layers (which may happens before we render something)
644 getDefaultDisplayDeviceLocked()->makeCurrent();
645
Steven Thomas050b2c82017-03-06 11:45:16 -0800646 if (useVrFlinger) {
647 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700648 // This callback is called from the vr flinger dispatch thread. We
649 // need to call signalTransaction(), which requires holding
650 // mStateLock when we're not on the main thread. Acquiring
651 // mStateLock from the vr flinger dispatch thread might trigger a
652 // deadlock in surface flinger (see b/66916578), so post a message
653 // to be handled on the main thread instead.
654 sp<LambdaMessage> message = new LambdaMessage([=]() {
655 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
656 mVrFlingerRequestsDisplay = requestDisplay;
657 signalTransaction();
658 });
659 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800660 };
David Sodman105b7dc2017-11-04 20:28:14 -0700661 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
662 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800663 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800664 if (!mVrFlinger) {
665 ALOGE("Failed to start vrflinger");
666 }
667 }
668
Lloyd Pique379adc12018-01-22 17:31:47 -0800669 mEventControlThread = std::make_unique<impl::EventControlThread>(
670 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700671
Mathias Agopian92a979a2012-08-02 18:32:23 -0700672 // initialize our drawing state
673 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700674
Andy McFadden13a082e2012-08-24 10:16:42 -0700675 // set initial conditions (e.g. unblank default device)
676 initializeDisplays();
David Sodman4b7c4bc2017-11-17 12:13:59 -0800677 ALOGV("Displays initialized");
Andy McFadden13a082e2012-08-24 10:16:42 -0700678
David Sodmanbc815282017-11-05 18:57:52 -0800679 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700680
Wei Wangf9b05ee2017-07-19 20:59:39 -0700681 // Inform native graphics APIs whether the present timestamp is supported:
682 if (getHwComposer().hasCapability(
683 HWC2::Capability::PresentFenceIsNotReliable)) {
684 mStartPropertySetThread = new StartPropertySetThread(false);
685 } else {
686 mStartPropertySetThread = new StartPropertySetThread(true);
687 }
688
689 if (mStartPropertySetThread->Start() != NO_ERROR) {
690 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800691 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800692
Dan Stoza9e56aa02015-11-02 13:00:03 -0800693 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700694}
695
Romain Guy11d63f42017-07-20 12:47:14 -0700696void SurfaceFlinger::readPersistentProperties() {
697 char value[PROPERTY_VALUE_MAX];
698
699 property_get("persist.sys.sf.color_saturation", value, "1.0");
700 mSaturation = atof(value);
701 ALOGV("Saturation is set to %.2f", mSaturation);
Romain Guy54f154a2017-10-24 21:40:32 +0100702
703 property_get("persist.sys.sf.native_mode", value, "0");
704 mForceNativeColorMode = atoi(value) == 1;
705 if (mForceNativeColorMode) {
706 ALOGV("Forcing native color mode");
707 }
Romain Guy11d63f42017-07-20 12:47:14 -0700708}
709
Mathias Agopiana67e4182012-06-19 17:26:12 -0700710void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800711 // Start boot animation service by setting a property mailbox
712 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700713 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800714 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700715 if (mStartPropertySetThread->join() != NO_ERROR) {
716 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800717 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700718}
719
Mathias Agopian875d8e12013-06-07 15:35:48 -0700720size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800721 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700722}
723
Mathias Agopian875d8e12013-06-07 15:35:48 -0700724size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800725 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700726}
727
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800728// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800729
Jamie Gennis582270d2011-08-17 18:19:00 -0700730bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800731 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800732 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800733 return authenticateSurfaceTextureLocked(bufferProducer);
734}
735
736bool SurfaceFlinger::authenticateSurfaceTextureLocked(
737 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800738 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800739 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800740}
741
Brian Anderson6b376712017-04-04 10:51:39 -0700742status_t SurfaceFlinger::getSupportedFrameTimestamps(
743 std::vector<FrameEvent>* outSupported) const {
744 *outSupported = {
745 FrameEvent::REQUESTED_PRESENT,
746 FrameEvent::ACQUIRE,
747 FrameEvent::LATCH,
748 FrameEvent::FIRST_REFRESH_START,
749 FrameEvent::LAST_REFRESH_START,
750 FrameEvent::GPU_COMPOSITION_DONE,
751 FrameEvent::DEQUEUE_READY,
752 FrameEvent::RELEASE,
753 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700754 ConditionalLock _l(mStateLock,
755 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700756 if (!getHwComposer().hasCapability(
757 HWC2::Capability::PresentFenceIsNotReliable)) {
758 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
759 }
760 return NO_ERROR;
761}
762
Dan Stoza7f7da322014-05-02 15:26:25 -0700763status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
764 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800765 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700766 return BAD_VALUE;
767 }
768
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500769 if (!display.get())
770 return NAME_NOT_FOUND;
771
Jesse Hall692c7232012-11-08 15:41:56 -0800772 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700773 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800774 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700775 type = i;
776 break;
777 }
778 }
779
780 if (type < 0) {
781 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700782 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700783
Mathias Agopian8b736f12012-08-13 17:54:26 -0700784 // TODO: Not sure if display density should handled by SF any longer
785 class Density {
786 static int getDensityFromProperty(char const* propName) {
787 char property[PROPERTY_VALUE_MAX];
788 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800789 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700790 density = atoi(property);
791 }
792 return density;
793 }
794 public:
795 static int getEmuDensity() {
796 return getDensityFromProperty("qemu.sf.lcd_density"); }
797 static int getBuildDensity() {
798 return getDensityFromProperty("ro.sf.lcd_density"); }
799 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700800
Dan Stoza7f7da322014-05-02 15:26:25 -0700801 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700802
Steven Thomas6d8110b2017-08-31 18:24:21 -0700803 ConditionalLock _l(mStateLock,
804 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800805 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700806 DisplayInfo info = DisplayInfo();
807
Dan Stoza9e56aa02015-11-02 13:00:03 -0800808 float xdpi = hwConfig->getDpiX();
809 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700810
811 if (type == DisplayDevice::DISPLAY_PRIMARY) {
812 // The density of the device is provided by a build property
813 float density = Density::getBuildDensity() / 160.0f;
814 if (density == 0) {
815 // the build doesn't provide a density -- this is wrong!
816 // use xdpi instead
817 ALOGE("ro.sf.lcd_density must be defined as a build property");
818 density = xdpi / 160.0f;
819 }
820 if (Density::getEmuDensity()) {
821 // if "qemu.sf.lcd_density" is specified, it overrides everything
822 xdpi = ydpi = density = Density::getEmuDensity();
823 density /= 160.0f;
824 }
825 info.density = density;
826
827 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700828 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800829 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700830 } else {
831 // TODO: where should this value come from?
832 static const int TV_DENSITY = 213;
833 info.density = TV_DENSITY / 160.0f;
834 info.orientation = 0;
835 }
836
Dan Stoza9e56aa02015-11-02 13:00:03 -0800837 info.w = hwConfig->getWidth();
838 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700839 info.xdpi = xdpi;
840 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800841 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900842 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800843
Andy McFadden91b2ca82014-06-13 14:04:23 -0700844 // This is how far in advance a buffer must be queued for
845 // presentation at a given time. If you want a buffer to appear
846 // on the screen at time N, you must submit the buffer before
847 // (N - presentationDeadline).
848 //
849 // Normally it's one full refresh period (to give SF a chance to
850 // latch the buffer), but this can be reduced by configuring a
851 // DispSync offset. Any additional delays introduced by the hardware
852 // composer or panel must be accounted for here.
853 //
854 // We add an additional 1ms to allow for processing time and
855 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800856 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800857 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700858
859 // All non-virtual displays are currently considered secure.
860 info.secure = true;
861
Michael Wright28f24d02016-07-12 13:30:53 -0700862 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700863 }
864
Dan Stoza7f7da322014-05-02 15:26:25 -0700865 return NO_ERROR;
866}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700867
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800868status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700869 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800870 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700871 return BAD_VALUE;
872 }
873
874 // FIXME for now we always return stats for the primary display
875 memset(stats, 0, sizeof(*stats));
876 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
877 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
878 return NO_ERROR;
879}
880
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700881int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800882 if (display == nullptr) {
883 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800884 return BAD_VALUE;
885 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700886
887 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800888 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700889 return device->getActiveConfig();
890 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700891
Dan Stoza24a42e92015-03-09 10:04:11 -0700892 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700893}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700894
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700895void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
896 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
897 this);
898 int32_t type = hw->getDisplayType();
899 int currentMode = hw->getActiveConfig();
900
901 if (mode == currentMode) {
902 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
903 return;
904 }
905
906 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
907 ALOGW("Trying to set config for virtual display");
908 return;
909 }
910
911 hw->setActiveConfig(mode);
912 getHwComposer().setActiveConfig(type, mode);
913}
914
915status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
916 class MessageSetActiveConfig: public MessageBase {
917 SurfaceFlinger& mFlinger;
918 sp<IBinder> mDisplay;
919 int mMode;
920 public:
921 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
922 int mode) :
923 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
924 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700925 Vector<DisplayInfo> configs;
926 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700927 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700928 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700929 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700930 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700931 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700932 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800933 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700934 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700935 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700936 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
937 ALOGW("Attempt to set active config = %d for virtual display",
938 mMode);
939 } else {
940 mFlinger.setActiveConfigInternal(hw, mMode);
941 }
942 return true;
943 }
944 };
945 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
946 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700947 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700948}
Michael Wright28f24d02016-07-12 13:30:53 -0700949status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -0700950 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700951 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
952 return BAD_VALUE;
953 }
954
955 if (!display.get()) {
956 return NAME_NOT_FOUND;
957 }
958
959 int32_t type = NAME_NOT_FOUND;
960 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
961 if (display == mBuiltinDisplays[i]) {
962 type = i;
963 break;
964 }
965 }
966
967 if (type < 0) {
968 return type;
969 }
970
Peiyong Lina52f0292018-03-14 17:26:31 -0700971 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700972 {
973 ConditionalLock _l(mStateLock,
974 std::this_thread::get_id() != mMainThreadId);
975 modes = getHwComposer().getColorModes(type);
976 }
Michael Wright28f24d02016-07-12 13:30:53 -0700977 outColorModes->clear();
978 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
979
980 return NO_ERROR;
981}
982
Peiyong Lina52f0292018-03-14 17:26:31 -0700983ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700984 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700985 if (device != nullptr) {
986 return device->getActiveColorMode();
987 }
Peiyong Lina52f0292018-03-14 17:26:31 -0700988 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -0700989}
990
991void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lina52f0292018-03-14 17:26:31 -0700992 ColorMode mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700993 int32_t type = hw->getDisplayType();
Peiyong Lina52f0292018-03-14 17:26:31 -0700994 ColorMode currentMode = hw->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -0700995
996 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700997 return;
998 }
999
1000 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1001 ALOGW("Trying to set config for virtual display");
1002 return;
1003 }
1004
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001005 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
1006 hw->getDisplayType());
1007
Michael Wright28f24d02016-07-12 13:30:53 -07001008 hw->setActiveColorMode(mode);
1009 getHwComposer().setActiveColorMode(type, mode);
1010}
1011
1012
1013status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001014 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -07001015 class MessageSetActiveColorMode: public MessageBase {
1016 SurfaceFlinger& mFlinger;
1017 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -07001018 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001019 public:
1020 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -07001021 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -07001022 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1023 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -07001024 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001025 mFlinger.getDisplayColorModes(mDisplay, &modes);
1026 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -07001027 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001028 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1029 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001030 return true;
1031 }
1032 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1033 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001034 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1035 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001036 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001037 ALOGW("Attempt to set active color mode %s %d for virtual display",
1038 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001039 } else {
1040 mFlinger.setActiveColorModeInternal(hw, mMode);
1041 }
1042 return true;
1043 }
1044 };
1045 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1046 postMessageSync(msg);
1047 return NO_ERROR;
1048}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001049
Svetoslavd85084b2014-03-20 10:28:31 -07001050status_t SurfaceFlinger::clearAnimationFrameStats() {
1051 Mutex::Autolock _l(mStateLock);
1052 mAnimFrameTracker.clearStats();
1053 return NO_ERROR;
1054}
1055
1056status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1057 Mutex::Autolock _l(mStateLock);
1058 mAnimFrameTracker.getStats(outStats);
1059 return NO_ERROR;
1060}
1061
Dan Stozac4f471e2016-03-24 09:31:08 -07001062status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1063 HdrCapabilities* outCapabilities) const {
1064 Mutex::Autolock _l(mStateLock);
1065
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001066 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001067 if (displayDevice == nullptr) {
1068 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1069 return BAD_VALUE;
1070 }
1071
1072 std::unique_ptr<HdrCapabilities> capabilities =
David Sodman105b7dc2017-11-04 20:28:14 -07001073 getBE().mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
Dan Stozac4f471e2016-03-24 09:31:08 -07001074 if (capabilities) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001075 if (displayDevice->getWideColorSupport() && !displayDevice->getHdrSupport()) {
1076 // insert HDR10 as we will force client composition for HDR10
1077 // layers
1078 std::vector<int32_t> types = capabilities->getSupportedHdrTypes();
1079 types.push_back(HAL_HDR_HDR10);
1080
1081 *outCapabilities = HdrCapabilities(types,
1082 capabilities->getDesiredMaxLuminance(),
1083 capabilities->getDesiredMaxAverageLuminance(),
1084 capabilities->getDesiredMinLuminance());
1085 } else {
1086 *outCapabilities = std::move(*capabilities);
1087 }
Dan Stozac4f471e2016-03-24 09:31:08 -07001088 } else {
1089 return BAD_VALUE;
1090 }
1091
1092 return NO_ERROR;
1093}
1094
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001095status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001096 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1097 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001098
Chia-I Wu90f669f2017-10-05 14:24:41 -07001099 if (mInjectVSyncs == enable) {
1100 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001101 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001102
1103 if (enable) {
1104 ALOGV("VSync Injections enabled");
1105 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001106 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique0fcde1b2017-12-20 16:50:21 -08001107 mInjectorEventThread =
1108 std::make_unique<impl::EventThread>(mVSyncInjector.get(), *this, false,
1109 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001110 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001111 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001112 } else {
1113 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001114 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001115 }
1116
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001117 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001118 });
1119 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001120 return NO_ERROR;
1121}
1122
1123status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001124 Mutex::Autolock _l(mStateLock);
1125
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001126 if (!mInjectVSyncs) {
1127 ALOGE("VSync Injections not enabled");
1128 return BAD_VALUE;
1129 }
1130 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1131 ALOGV("Injecting VSync inside SurfaceFlinger");
1132 mVSyncInjector->onInjectSyncEvent(when);
1133 }
1134 return NO_ERROR;
1135}
1136
Lloyd Pique755e3192018-01-31 16:46:15 -08001137status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1138 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001139 IPCThreadState* ipc = IPCThreadState::self();
1140 const int pid = ipc->getCallingPid();
1141 const int uid = ipc->getCallingUid();
1142 if ((uid != AID_SHELL) &&
1143 !PermissionCache::checkPermission(sDump, pid, uid)) {
1144 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1145 return PERMISSION_DENIED;
1146 }
1147
1148 // Try to acquire a lock for 1s, fail gracefully
1149 const status_t err = mStateLock.timedLock(s2ns(1));
1150 const bool locked = (err == NO_ERROR);
1151 if (!locked) {
1152 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1153 return TIMED_OUT;
1154 }
1155
1156 outLayers->clear();
1157 mCurrentState.traverseInZOrder([&](Layer* layer) {
1158 outLayers->push_back(layer->getLayerDebugInfo());
1159 });
1160
1161 mStateLock.unlock();
1162 return NO_ERROR;
1163}
1164
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001165// ----------------------------------------------------------------------------
1166
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001167sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1168 ISurfaceComposer::VsyncSource vsyncSource) {
1169 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1170 return mSFEventThread->createEventConnection();
1171 } else {
1172 return mEventThread->createEventConnection();
1173 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001174}
1175
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001176// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001177
1178void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001179 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001180}
1181
1182void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001183 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001184}
1185
1186void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001187 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001188}
1189
1190void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001191 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001192 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001193}
1194
1195status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001196 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001197 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001198}
1199
1200status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001201 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001202 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001203 if (res == NO_ERROR) {
1204 msg->wait();
1205 }
1206 return res;
1207}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001208
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001209void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001210 do {
1211 waitForEvent();
1212 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001213}
1214
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001215void SurfaceFlinger::enableHardwareVsync() {
1216 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001217 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001218 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001219 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1220 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001221 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001222 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001223}
1224
Jesse Hall948fe0c2013-10-14 12:56:09 -07001225void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001226 Mutex::Autolock _l(mHWVsyncLock);
1227
Jesse Hall948fe0c2013-10-14 12:56:09 -07001228 if (makeAvailable) {
1229 mHWVsyncAvailable = true;
1230 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001231 // Hardware vsync is not currently available, so abort the resync
1232 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001233 return;
1234 }
1235
David Sodman105b7dc2017-11-04 20:28:14 -07001236 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001237 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001238
1239 mPrimaryDispSync.reset();
1240 mPrimaryDispSync.setPeriod(period);
1241
1242 if (!mPrimaryHWVsyncEnabled) {
1243 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001244 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1245 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001246 mPrimaryHWVsyncEnabled = true;
1247 }
1248}
1249
Jesse Hall948fe0c2013-10-14 12:56:09 -07001250void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001251 Mutex::Autolock _l(mHWVsyncLock);
1252 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001253 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1254 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001255 mPrimaryDispSync.endResync();
1256 mPrimaryHWVsyncEnabled = false;
1257 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001258 if (makeUnavailable) {
1259 mHWVsyncAvailable = false;
1260 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001261}
1262
Tim Murray4a4e4a22016-04-19 16:29:23 +00001263void SurfaceFlinger::resyncWithRateLimit() {
1264 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001265
1266 // No explicit locking is needed here since EventThread holds a lock while calling this method
1267 static nsecs_t sLastResyncAttempted = 0;
1268 const nsecs_t now = systemTime();
1269 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001270 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001271 }
Dan Stoza57164302017-05-08 14:03:54 -07001272 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001273}
1274
Steven Thomasb02664d2017-07-26 18:48:28 -07001275void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1276 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001277 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001278 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001279 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001280 return;
1281 }
1282
1283 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001284 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001285 return;
1286 }
1287
Jamie Gennisd1700752013-10-14 12:22:52 -07001288 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001289
Jamie Gennisd1700752013-10-14 12:22:52 -07001290 { // Scope for the lock
1291 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001292 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001293 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001294 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001295 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001296
1297 if (needsHwVsync) {
1298 enableHardwareVsync();
1299 } else {
1300 disableHardwareVsync(false);
1301 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001302}
1303
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001304void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001305 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1306 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001307}
1308
Lloyd Pique715a2c12017-12-14 17:18:08 -08001309void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1310 HWC2::Connection connection) {
1311 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1312 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001313
Lloyd Piqueba04e622017-12-14 17:11:26 -08001314 // Ignore events that do not have the right sequenceId.
1315 if (sequenceId != getBE().mComposerSequenceId) {
1316 return;
1317 }
1318
Steven Thomasb02664d2017-07-26 18:48:28 -07001319 // Only lock if we're not on the main thread. This function is normally
1320 // called on a hwbinder thread, but for the primary display it's called on
1321 // the main thread with the state lock already held, so don't attempt to
1322 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001323 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001324
Lloyd Pique715a2c12017-12-14 17:18:08 -08001325 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001326
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001327 if (std::this_thread::get_id() == mMainThreadId) {
1328 // Process all pending hot plug events immediately if we are on the main thread.
1329 processDisplayHotplugEventsLocked();
1330 }
1331
Lloyd Piqueba04e622017-12-14 17:11:26 -08001332 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001333}
1334
Steven Thomasb02664d2017-07-26 18:48:28 -07001335void SurfaceFlinger::onRefreshReceived(int sequenceId,
1336 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001337 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001338 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001339 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001340 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001341 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001342}
1343
Dan Stoza9e56aa02015-11-02 13:00:03 -08001344void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001345 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001346 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001347 getHwComposer().setVsyncEnabled(disp,
1348 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001349}
1350
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001351// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001352void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001353 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001354 // Clear the drawing state so that the logic inside of
1355 // handleTransactionLocked will fire. It will determine the delta between
1356 // mCurrentState and mDrawingState and re-apply all changes when we make the
1357 // transition.
1358 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001359 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001360 mDisplays.clear();
1361}
1362
Steven Thomas050b2c82017-03-06 11:45:16 -08001363void SurfaceFlinger::updateVrFlinger() {
1364 if (!mVrFlinger)
1365 return;
1366 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001367 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001368 return;
1369 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001370
David Sodman105b7dc2017-11-04 20:28:14 -07001371 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001372 ALOGE("Vr flinger is only supported for remote hardware composer"
1373 " service connections. Ignoring request to transition to vr"
1374 " flinger.");
1375 mVrFlingerRequestsDisplay = false;
1376 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001377 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001378
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001379 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001380
Steven Thomasb02664d2017-07-26 18:48:28 -07001381 int currentDisplayPowerMode = getDisplayDeviceLocked(
1382 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001383
Steven Thomasb02664d2017-07-26 18:48:28 -07001384 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001385 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001386 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001387
Steven Thomasb02664d2017-07-26 18:48:28 -07001388 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001389 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001390 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1391 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001392 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001393
David Sodman105b7dc2017-11-04 20:28:14 -07001394 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1395 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001396
1397 if (vrFlingerRequestsDisplay) {
1398 mVrFlinger->GrantDisplayOwnership();
1399 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001400 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001401 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001402
1403 mVisibleRegionsDirty = true;
1404 invalidateHwcGeometry();
1405
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001406 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001407 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1408 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1409 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001410
Steven Thomasb02664d2017-07-26 18:48:28 -07001411 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001412 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001413 const nsecs_t period = activeConfig->getVsyncPeriod();
1414 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001415
Steven Thomasb02664d2017-07-26 18:48:28 -07001416 // Use phase of 0 since phase is not known.
1417 // Use latency of 0, which will snap to the ideal latency.
1418 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001419
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001420 android_atomic_or(1, &mRepaintEverything);
1421 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001422}
1423
Mathias Agopian4fec8732012-06-29 14:12:52 -07001424void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001425 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001426 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001427 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001428 bool frameMissed = !mHadClientComposition &&
1429 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001430 (mPreviousPresentFence->getSignalTime() ==
1431 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001432 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001433 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001434 signalLayerUpdate();
1435 break;
1436 }
1437
Steven Thomas050b2c82017-03-06 11:45:16 -08001438 // Now that we're going to make it to the handleMessageTransaction()
1439 // call below it's safe to call updateVrFlinger(), which will
1440 // potentially trigger a display handoff.
1441 updateVrFlinger();
1442
Dan Stoza6b9454d2014-11-07 16:00:59 -08001443 bool refreshNeeded = handleMessageTransaction();
1444 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001445 refreshNeeded |= mRepaintEverything;
David Sodman56912832017-11-28 10:27:38 -08001446
David Sodman4bfd3972017-12-15 13:33:47 -08001447 preComposition();
David Sodman56912832017-11-28 10:27:38 -08001448 rebuildLayerStacks();
David Sodman56912832017-11-28 10:27:38 -08001449 calculateWorkingSet();
1450
Dan Stoza6b9454d2014-11-07 16:00:59 -08001451 if (refreshNeeded) {
David Sodman56912832017-11-28 10:27:38 -08001452
Dan Stoza58784442014-12-02 16:58:17 -08001453 // Signal a refresh if a transaction modified the window state,
1454 // a new buffer was latched, or if HWC has requested a full
1455 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001456 signalRefresh();
1457 }
1458 break;
1459 }
1460 case MessageQueue::REFRESH: {
1461 handleMessageRefresh();
1462 break;
1463 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001464 }
1465}
1466
Dan Stoza6b9454d2014-11-07 16:00:59 -08001467bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001468 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001469 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001470 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001471 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001472 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001473 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001474}
1475
Dan Stoza6b9454d2014-11-07 16:00:59 -08001476bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001477 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001478 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001479}
1480
David Sodman56912832017-11-28 10:27:38 -08001481void SurfaceFlinger::calculateWorkingSet() {
1482 ATRACE_CALL();
1483 ALOGV(__FUNCTION__);
1484
1485 // build the h/w work list
1486 if (CC_UNLIKELY(mGeometryInvalid)) {
1487 mGeometryInvalid = false;
1488 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1489 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1490 const auto hwcId = displayDevice->getHwcDisplayId();
1491 if (hwcId >= 0) {
1492 const Vector<sp<Layer>>& currentLayers(
1493 displayDevice->getVisibleLayersSortedByZ());
1494 for (size_t i = 0; i < currentLayers.size(); i++) {
1495 const auto& layer = currentLayers[i];
1496
1497 if (!layer->hasHwcLayer(hwcId)) {
1498 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
1499 layer->forceClientComposition(hwcId);
1500 continue;
1501 }
1502 }
1503
1504 layer->setGeometry(displayDevice, i);
1505 if (mDebugDisableHWC || mDebugRegion) {
1506 layer->forceClientComposition(hwcId);
1507 }
1508 }
1509 }
1510 }
1511 }
1512 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
1513
1514 // Set the per-frame data
1515 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1516 auto& displayDevice = mDisplays[displayId];
1517 const auto hwcId = displayDevice->getHwcDisplayId();
1518
1519 if (hwcId < 0) {
1520 continue;
1521 }
1522 if (colorMatrix != mPreviousColorMatrix) {
1523 status_t result = getBE().mHwc->setColorTransform(hwcId, colorMatrix);
1524 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1525 "display %zd: %d", displayId, result);
1526 }
1527 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1528 if ((layer->getDataSpace() == HAL_DATASPACE_BT2020_PQ ||
1529 layer->getDataSpace() == HAL_DATASPACE_BT2020_ITU_PQ) &&
1530 !displayDevice->getHdrSupport()) {
1531 layer->forceClientComposition(hwcId);
1532 }
1533
1534 if (layer->getForceClientComposition(hwcId)) {
1535 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1536 layer->setCompositionType(hwcId, HWC2::Composition::Client);
1537 continue;
1538 }
1539
1540 layer->setPerFrameData(displayDevice);
1541 }
1542
1543 if (hasWideColorDisplay) {
1544 ColorMode newColorMode;
1545 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1546
1547 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1548 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace,
1549 displayDevice->getHdrSupport());
1550 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1551 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1552 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1553 }
1554 newColorMode = pickColorMode(newDataSpace);
1555
1556 setActiveColorModeInternal(displayDevice, newColorMode);
1557 }
1558 }
1559
1560 mPreviousColorMatrix = colorMatrix;
1561 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1562 auto& displayDevice = mDisplays[displayId];
1563 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1564 auto hwcId = displayDevice->getHwcDisplayId();
1565 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(hwcId);
1566 if (!layer->setHwcLayer(hwcId)) {
1567 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1568 }
1569 layer->getBE().compositionInfo.hwc.hwid = hwcId;
1570 getBE().mCompositionInfo.push_back(layer->getBE().compositionInfo);
1571 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1572 }
1573 }
1574}
1575
Mathias Agopian4fec8732012-06-29 14:12:52 -07001576void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001577 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001578
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001579 mRefreshPending = false;
1580
Dan Stoza14cd37c2015-07-09 12:43:33 -07001581
David Sodman4bfd3972017-12-15 13:33:47 -08001582
1583 beginFrame();
1584 for (auto compositionInfo : getBE().mCompositionInfo) {
1585 setUpHWComposer(compositionInfo);
1586 }
1587 prepareFrame();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001588 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001589 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001590 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001591 doComposition();
David Sodman4bfd3972017-12-15 13:33:47 -08001592 postComposition();
1593
1594 getBE().mCompositionInfo.clear();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001595
David Sodman105b7dc2017-11-04 20:28:14 -07001596 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001597
1598 mHadClientComposition = false;
1599 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1600 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1601 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001602 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001603 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001604
Dan Stoza9e56aa02015-11-02 13:00:03 -08001605 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001606}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001607
Mathias Agopiancd60f992012-08-16 16:28:27 -07001608void SurfaceFlinger::doDebugFlashRegions()
1609{
1610 // is debugging enabled
1611 if (CC_LIKELY(!mDebugRegion))
1612 return;
1613
1614 const bool repaintEverything = mRepaintEverything;
1615 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1616 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001617 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001618 // transform the dirty region into this screen's coordinate space
1619 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1620 if (!dirtyRegion.isEmpty()) {
1621 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001622 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001623
1624 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001625 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001626 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001627 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1628
Mathias Agopianda27af92012-09-13 18:17:13 -07001629 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001630 }
1631 }
1632 }
1633
1634 postFramebuffer();
1635
1636 if (mDebugRegion > 1) {
1637 usleep(mDebugRegion * 1000);
1638 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001639
Dan Stoza9e56aa02015-11-02 13:00:03 -08001640 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001641 auto& displayDevice = mDisplays[displayId];
1642 if (!displayDevice->isDisplayOn()) {
1643 continue;
1644 }
1645
David Sodman105b7dc2017-11-04 20:28:14 -07001646 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1647 ALOGE_IF(result != NO_ERROR,
1648 "prepareFrame for display %zd failed:"
1649 " %d (%s)",
1650 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001651 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001652}
1653
Adrian Roos1e1a1282017-11-01 19:05:31 +01001654void SurfaceFlinger::doTracing(const char* where) {
1655 ATRACE_CALL();
1656 ATRACE_NAME(where);
1657 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001658 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001659 }
1660}
1661
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001662void SurfaceFlinger::logLayerStats() {
1663 ATRACE_CALL();
1664 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1665 int32_t hwcId = -1;
1666 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1667 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1668 if (displayDevice->isPrimary()) {
1669 hwcId = displayDevice->getHwcDisplayId();
1670 break;
1671 }
1672 }
1673 if (hwcId < 0) {
1674 ALOGE("LayerStats: Hmmm, no primary display?");
1675 return;
1676 }
1677 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1678 }
1679}
1680
David Sodman4bfd3972017-12-15 13:33:47 -08001681void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001682{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001683 ATRACE_CALL();
1684 ALOGV("preComposition");
1685
Mathias Agopiancd60f992012-08-16 16:28:27 -07001686 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001687 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman4bfd3972017-12-15 13:33:47 -08001688 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001689 needExtraInvalidate = true;
1690 }
Robert Carr2047fae2016-11-28 14:09:09 -08001691 });
1692
Mathias Agopiancd60f992012-08-16 16:28:27 -07001693 if (needExtraInvalidate) {
1694 signalLayerUpdate();
1695 }
1696}
1697
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001698void SurfaceFlinger::updateCompositorTiming(
1699 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1700 std::shared_ptr<FenceTime>& presentFenceTime) {
1701 // Update queue of past composite+present times and determine the
1702 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001703 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001704 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001705 while (!getBE().mCompositePresentTimes.empty()) {
1706 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001707 // Cached values should have been updated before calling this method,
1708 // which helps avoid duplicate syscalls.
1709 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1710 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1711 break;
1712 }
1713 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001714 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001715 }
1716
1717 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001718 while (getBE().mCompositePresentTimes.size() > 16) {
1719 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001720 }
1721
Brian Andersond0010582017-03-07 13:20:31 -08001722 setCompositorTimingSnapped(
1723 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1724}
1725
1726void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1727 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001728 // Integer division and modulo round toward 0 not -inf, so we need to
1729 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001730 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001731 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1732 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1733
Brian Andersond0010582017-03-07 13:20:31 -08001734 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1735 if (idealLatency <= 0) {
1736 idealLatency = vsyncInterval;
1737 }
1738
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001739 // Snap the latency to a value that removes scheduling jitter from the
1740 // composition and present times, which often have >1ms of jitter.
1741 // Reducing jitter is important if an app attempts to extrapolate
1742 // something (such as user input) to an accurate diasplay time.
1743 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1744 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001745 nsecs_t bias = vsyncInterval / 2;
1746 int64_t extraVsyncs =
1747 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1748 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1749 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001750
David Sodman99974d22017-11-28 12:04:33 -08001751 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1752 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1753 getBE().mCompositorTiming.interval = vsyncInterval;
1754 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001755}
1756
David Sodman4bfd3972017-12-15 13:33:47 -08001757void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001758{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001759 ATRACE_CALL();
1760 ALOGV("postComposition");
1761
Brian Anderson3546a3f2016-07-14 11:51:14 -07001762 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001763 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001764 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001765 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001766 }
1767
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001768 // |mStateLock| not needed as we are on the main thread
1769 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001770
David Sodman73beded2017-11-15 11:56:06 -08001771 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001772 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001773 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001774 glCompositionDoneFenceTime =
1775 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001776 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001777 } else {
1778 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1779 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001780
David Sodman73beded2017-11-15 11:56:06 -08001781 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001782 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001783 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001784 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001785
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001786 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1787 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1788
David Sodman4bfd3972017-12-15 13:33:47 -08001789 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001790 // when we started doing work for this frame, but that should be okay
1791 // since updateCompositorTiming has snapping logic.
1792 updateCompositorTiming(
David Sodman4bfd3972017-12-15 13:33:47 -08001793 vsyncPhase, vsyncInterval, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001794 CompositorTiming compositorTiming;
1795 {
David Sodman99974d22017-11-28 12:04:33 -08001796 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1797 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001798 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001799
Robert Carr2047fae2016-11-28 14:09:09 -08001800 mDrawingState.traverseInZOrder([&](Layer* layer) {
1801 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001802 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001803 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001804 recordBufferingStats(layer->getName().string(),
1805 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001806 }
Robert Carr2047fae2016-11-28 14:09:09 -08001807 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001808
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001809 if (presentFenceTime->isValid()) {
1810 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001811 enableHardwareVsync();
1812 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001813 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001814 }
1815 }
1816
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001817 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001818 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001819 enableHardwareVsync();
1820 }
1821 }
1822
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001823 if (mAnimCompositionPending) {
1824 mAnimCompositionPending = false;
1825
Brian Anderson4e606e32017-03-16 15:34:57 -07001826 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001827 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001828 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001829 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001830 // The HWC doesn't support present fences, so use the refresh
1831 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001832 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001833 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001834 mAnimFrameTracker.setActualPresentTime(presentTime);
1835 }
1836 mAnimFrameTracker.advanceFrame();
1837 }
Dan Stozab90cf072015-03-05 11:05:59 -08001838
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001839 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1840 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001841 return;
1842 }
1843
1844 nsecs_t currentTime = systemTime();
1845 if (mHasPoweredOff) {
1846 mHasPoweredOff = false;
1847 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001848 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001849 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001850 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1851 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001852 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001853 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001854 }
David Sodman4a36e932017-11-07 14:29:47 -08001855 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001856 }
David Sodman4a36e932017-11-07 14:29:47 -08001857 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001858}
1859
1860void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001861 ATRACE_CALL();
1862 ALOGV("rebuildLayerStacks");
1863
Mathias Agopiancd60f992012-08-16 16:28:27 -07001864 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001865 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001866 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001867 mVisibleRegionsDirty = false;
1868 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001869
Jeff Sharkey76488112017-02-27 14:15:18 -07001870 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1871 Region opaqueRegion;
1872 Region dirtyRegion;
1873 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001874 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001875 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1876 const Transform& tr(displayDevice->getTransform());
1877 const Rect bounds(displayDevice->getBounds());
1878 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001879 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001880
Jeff Sharkey76488112017-02-27 14:15:18 -07001881 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001882 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001883 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1884 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001885 Region drawRegion(tr.transform(
1886 layer->visibleNonTransparentRegion));
1887 drawRegion.andSelf(bounds);
1888 if (!drawRegion.isEmpty()) {
1889 layersSortedByZ.add(layer);
1890 } else {
David Sodman56912832017-11-28 10:27:38 -08001891 if (layer->hasHwcLayer(displayDevice->getHwcDisplayId())) {
1892 // Clear out the HWC layer if this layer was
1893 // previously visible, but no longer is
1894 hwcLayerDestroyed = layer->destroyHwcLayer(
1895 displayDevice->getHwcDisplayId());
1896 }
1897 }
1898 } else {
1899 if (layer->hasHwcLayer(displayDevice->getHwcDisplayId())) {
1900 // WM changes displayDevice->layerStack upon sleep/awake.
1901 // Here we make sure we delete the HWC layers even if
1902 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001903 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001904 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001905 }
Chia-I Wu83806892017-11-16 10:50:20 -08001906 }
1907
1908 // If a layer is not going to get a release fence because
1909 // it is invisible, but it is also going to release its
1910 // old buffer, add it to the list of layers needing
1911 // fences.
1912 if (hwcLayerDestroyed) {
1913 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1914 mLayersWithQueuedFrames.cend(), layer);
1915 if (found != mLayersWithQueuedFrames.cend()) {
1916 layersNeedingFences.add(layer);
1917 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001918 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001919 });
1920 }
1921 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001922 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001923 displayDevice->undefinedRegion.set(bounds);
1924 displayDevice->undefinedRegion.subtractSelf(
1925 tr.transform(opaqueRegion));
1926 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001927 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001928 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001929}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001930
Romain Guy0147a172017-06-01 13:53:56 -07001931mat4 SurfaceFlinger::computeSaturationMatrix() const {
1932 if (mSaturation == 1.0f) {
1933 return mat4();
1934 }
1935
1936 // Rec.709 luma coefficients
1937 float3 luminance{0.213f, 0.715f, 0.072f};
1938 luminance *= 1.0f - mSaturation;
1939 return mat4(
1940 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1941 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1942 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1943 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1944 );
1945}
1946
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001947// pickColorMode translates a given dataspace into the best available color mode.
1948// Currently only support sRGB and Display-P3.
Peiyong Lina52f0292018-03-14 17:26:31 -07001949ColorMode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Romain Guy54f154a2017-10-24 21:40:32 +01001950 if (mForceNativeColorMode) {
Peiyong Lina52f0292018-03-14 17:26:31 -07001951 return ColorMode::NATIVE;
Romain Guy54f154a2017-10-24 21:40:32 +01001952 }
1953
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001954 switch (dataSpace) {
1955 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1956 // system expects.
1957 case HAL_DATASPACE_UNKNOWN:
1958 case HAL_DATASPACE_SRGB:
1959 case HAL_DATASPACE_V0_SRGB:
Peiyong Lina52f0292018-03-14 17:26:31 -07001960 return ColorMode::SRGB;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001961 break;
1962
1963 case HAL_DATASPACE_DISPLAY_P3:
Peiyong Lina52f0292018-03-14 17:26:31 -07001964 return ColorMode::DISPLAY_P3;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001965 break;
1966
1967 default:
1968 // TODO (courtneygo): Do we want to assert an error here?
1969 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1970 dataSpace);
Peiyong Lina52f0292018-03-14 17:26:31 -07001971 return ColorMode::SRGB;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001972 break;
1973 }
1974}
1975
Romain Guy0147a172017-06-01 13:53:56 -07001976android_dataspace SurfaceFlinger::bestTargetDataSpace(
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001977 android_dataspace a, android_dataspace b, bool hasHdr) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001978 // Only support sRGB and Display-P3 right now.
1979 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1980 return HAL_DATASPACE_DISPLAY_P3;
1981 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001982 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1983 return HAL_DATASPACE_DISPLAY_P3;
1984 }
1985 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1986 return HAL_DATASPACE_DISPLAY_P3;
1987 }
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001988 if (!hasHdr) {
1989 if (a == HAL_DATASPACE_BT2020_PQ || b == HAL_DATASPACE_BT2020_PQ) {
1990 return HAL_DATASPACE_DISPLAY_P3;
1991 }
1992 if (a == HAL_DATASPACE_BT2020_ITU_PQ || b == HAL_DATASPACE_BT2020_ITU_PQ) {
1993 return HAL_DATASPACE_DISPLAY_P3;
1994 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001995 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001996
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001997 return HAL_DATASPACE_V0_SRGB;
1998}
1999
David Sodman5a5f1482017-12-15 11:11:59 -08002000void SurfaceFlinger::configureSidebandComposition(const CompositionInfo& compositionInfo) const
2001{
2002 HWC2::Error error;
2003 LOG_ALWAYS_FATAL_IF(compositionInfo.hwc.sidebandStream == nullptr,
2004 "CompositionType is sideband, but sideband stream is nullptr");
2005 error = (*compositionInfo.hwc.hwcLayer)
2006 ->setSidebandStream(compositionInfo.hwc.sidebandStream->handle());
2007 if (error != HWC2::Error::None) {
2008 ALOGE("[SF] Failed to set sideband stream %p: %s (%d)",
2009 compositionInfo.hwc.sidebandStream->handle(), to_string(error).c_str(),
2010 static_cast<int32_t>(error));
2011 }
2012}
2013
David Sodman14fe0362017-12-14 17:31:04 -08002014void SurfaceFlinger::configureHwcCommonData(const CompositionInfo& compositionInfo) const
David Sodman56912832017-11-28 10:27:38 -08002015{
2016 HWC2::Error error;
2017
2018 if (!compositionInfo.hwc.skipGeometry) {
David Sodman14fe0362017-12-14 17:31:04 -08002019 error = (*compositionInfo.hwc.hwcLayer)->setBlendMode(compositionInfo.hwc.blendMode);
2020 ALOGE_IF(error != HWC2::Error::None,
2021 "[SF] Failed to set blend mode %s:"
2022 " %s (%d)",
2023 to_string(compositionInfo.hwc.blendMode).c_str(), to_string(error).c_str(),
2024 static_cast<int32_t>(error));
David Sodman56912832017-11-28 10:27:38 -08002025
David Sodman14fe0362017-12-14 17:31:04 -08002026 error = (*compositionInfo.hwc.hwcLayer)->setDisplayFrame(compositionInfo.hwc.displayFrame);
2027 ALOGE_IF(error != HWC2::Error::None,
2028 "[SF] Failed to set the display frame [%d, %d, %d, %d] %s (%d)",
2029 compositionInfo.hwc.displayFrame.left,
2030 compositionInfo.hwc.displayFrame.right,
2031 compositionInfo.hwc.displayFrame.top,
2032 compositionInfo.hwc.displayFrame.bottom,
2033 to_string(error).c_str(), static_cast<int32_t>(error));
David Sodman56912832017-11-28 10:27:38 -08002034
David Sodman14fe0362017-12-14 17:31:04 -08002035 error = (*compositionInfo.hwc.hwcLayer)->setSourceCrop(compositionInfo.hwc.sourceCrop);
2036 ALOGE_IF(error != HWC2::Error::None,
2037 "[SF] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: %s (%d)",
2038 compositionInfo.hwc.sourceCrop.left,
2039 compositionInfo.hwc.sourceCrop.right,
2040 compositionInfo.hwc.sourceCrop.top,
2041 compositionInfo.hwc.sourceCrop.bottom,
2042 to_string(error).c_str(), static_cast<int32_t>(error));
David Sodman56912832017-11-28 10:27:38 -08002043
2044 error = (*compositionInfo.hwc.hwcLayer)->setPlaneAlpha(compositionInfo.hwc.alpha);
2045 ALOGE_IF(error != HWC2::Error::None,
2046 "[SF] Failed to set plane alpha %.3f: "
2047 "%s (%d)",
2048 compositionInfo.hwc.alpha,
2049 to_string(error).c_str(), static_cast<int32_t>(error));
2050
2051
2052 error = (*compositionInfo.hwc.hwcLayer)->setZOrder(compositionInfo.hwc.z);
2053 ALOGE_IF(error != HWC2::Error::None,
2054 "[SF] Failed to set Z %u: %s (%d)",
2055 compositionInfo.hwc.z,
2056 to_string(error).c_str(), static_cast<int32_t>(error));
2057
David Sodman14fe0362017-12-14 17:31:04 -08002058 error = (*compositionInfo.hwc.hwcLayer)
2059 ->setInfo(compositionInfo.hwc.type, compositionInfo.hwc.appId);
David Sodman56912832017-11-28 10:27:38 -08002060 ALOGE_IF(error != HWC2::Error::None,
2061 "[SF] Failed to set info (%d)",
2062 static_cast<int32_t>(error));
2063
David Sodman14fe0362017-12-14 17:31:04 -08002064 error = (*compositionInfo.hwc.hwcLayer)->setTransform(compositionInfo.hwc.transform);
David Sodman56912832017-11-28 10:27:38 -08002065 ALOGE_IF(error != HWC2::Error::None,
David Sodman14fe0362017-12-14 17:31:04 -08002066 "[SF] Failed to set transform %s: "
2067 "%s (%d)",
2068 to_string(compositionInfo.hwc.transform).c_str(), to_string(error).c_str(),
2069 static_cast<int32_t>(error));
David Sodman56912832017-11-28 10:27:38 -08002070 }
2071
2072 error = (*compositionInfo.hwc.hwcLayer)->setCompositionType(compositionInfo.compositionType);
2073 ALOGE_IF(error != HWC2::Error::None,
2074 "[SF] Failed to set composition type: %s (%d)",
David Sodman14fe0362017-12-14 17:31:04 -08002075 to_string(error).c_str(), static_cast<int32_t>(error));
David Sodman56912832017-11-28 10:27:38 -08002076
2077 error = (*compositionInfo.hwc.hwcLayer)->setDataspace(compositionInfo.hwc.dataspace);
2078 ALOGE_IF(error != HWC2::Error::None,
2079 "[SF] Failed to set dataspace: %s (%d)",
2080 to_string(error).c_str(), static_cast<int32_t>(error));
2081
2082 error = (*compositionInfo.hwc.hwcLayer)->setHdrMetadata(compositionInfo.hwc.hdrMetadata);
2083 ALOGE_IF(error != HWC2::Error::None && error != HWC2::Error::Unsupported,
2084 "[SF] Failed to set hdrMetadata: %s (%d)",
2085 to_string(error).c_str(), static_cast<int32_t>(error));
2086
David Sodman14fe0362017-12-14 17:31:04 -08002087 error = (*compositionInfo.hwc.hwcLayer)->setColor(compositionInfo.hwc.color);
2088 ALOGE_IF(error != HWC2::Error::None,
2089 "[SF] Failed to set color: %s (%d)",
2090 to_string(error).c_str(), static_cast<int32_t>(error));
2091
2092 error = (*compositionInfo.hwc.hwcLayer)->setVisibleRegion(compositionInfo.hwc.visibleRegion);
2093 ALOGE_IF(error != HWC2::Error::None,
2094 "[SF] Failed to set visible region: %s (%d)",
2095 to_string(error).c_str(), static_cast<int32_t>(error));
2096}
2097
2098void SurfaceFlinger::configureDeviceComposition(const CompositionInfo& compositionInfo) const
2099{
2100 HWC2::Error error;
2101
2102 error = (*compositionInfo.hwc.hwcLayer)->setSurfaceDamage(compositionInfo.hwc.surfaceDamage);
2103 ALOGE_IF(error != HWC2::Error::None,
2104 "[SF] Failed to set surface damage: %s (%d)",
2105 to_string(error).c_str(), static_cast<int32_t>(error));
2106
David Sodman4bfd3972017-12-15 13:33:47 -08002107 error = (*compositionInfo.hwc.hwcLayer)->setBuffer(compositionInfo.mBufferSlot,
2108 compositionInfo.mBuffer, compositionInfo.hwc.fence);
2109 ALOGE_IF(error != HWC2::Error::None,
2110 "[SF] Failed to set buffer: %s (%d)",
2111 to_string(error).c_str(), static_cast<int32_t>(error));
David Sodman56912832017-11-28 10:27:38 -08002112}
2113
David Sodman4bfd3972017-12-15 13:33:47 -08002114void SurfaceFlinger::beginFrame()
2115{
2116 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002117
Jesse Hall028dc8f2013-08-20 16:35:32 -07002118 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07002119 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
2120 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
2121 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
2122
2123 // If nothing has changed (!dirty), don't recompose.
2124 // If something changed, but we don't currently have any visible layers,
2125 // and didn't when we last did a composition, then skip it this time.
2126 // The second rule does two things:
2127 // - When all layers are removed from a display, we'll emit one black
2128 // frame, then nothing more until we get new layers.
2129 // - When a display is created with a private layer stack, we won't
2130 // emit any black frames until a layer is added to the layer stack.
2131 bool mustRecompose = dirty && !(empty && wasEmpty);
2132
2133 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2134 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
2135 mustRecompose ? "doing" : "skipping",
2136 dirty ? "+" : "-",
2137 empty ? "+" : "-",
2138 wasEmpty ? "+" : "-");
2139
Dan Stoza71433162014-02-04 16:22:36 -08002140 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07002141
2142 if (mustRecompose) {
2143 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
2144 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07002145 }
David Sodman4bfd3972017-12-15 13:33:47 -08002146}
Jesse Hall028dc8f2013-08-20 16:35:32 -07002147
David Sodman4bfd3972017-12-15 13:33:47 -08002148void SurfaceFlinger::prepareFrame()
2149{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002150 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002151 auto& displayDevice = mDisplays[displayId];
2152 if (!displayDevice->isDisplayOn()) {
2153 continue;
2154 }
2155
David Sodman105b7dc2017-11-04 20:28:14 -07002156 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002157 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2158 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002159 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002160}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002161
David Sodman4bfd3972017-12-15 13:33:47 -08002162void SurfaceFlinger::setUpHWComposer(const CompositionInfo& compositionInfo) {
2163 ATRACE_CALL();
2164 ALOGV("setUpHWComposer");
2165
2166 switch (compositionInfo.compositionType)
2167 {
2168 case HWC2::Composition::Invalid:
2169 case HWC2::Composition::Client:
2170 case HWC2::Composition::Cursor:
2171 break;
2172
2173 case HWC2::Composition::Sideband:
2174 configureSidebandComposition(compositionInfo);
2175 break;
2176
2177 case HWC2::Composition::SolidColor:
2178 configureHwcCommonData(compositionInfo);
2179 break;
2180
2181 case HWC2::Composition::Device:
2182 configureHwcCommonData(compositionInfo);
2183 configureDeviceComposition(compositionInfo);
2184 break;
2185 }
2186}
2187
Mathias Agopiancd60f992012-08-16 16:28:27 -07002188void SurfaceFlinger::doComposition() {
2189 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002190 ALOGV("doComposition");
2191
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002192 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002193 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002194 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002195 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002196 // transform the dirty region into this screen's coordinate space
2197 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002198
2199 // repaint the framebuffer (if needed)
2200 doDisplayComposition(hw, dirtyRegion);
2201
Mathias Agopiancd60f992012-08-16 16:28:27 -07002202 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002203 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002204 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002205 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002206 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002207}
2208
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002209void SurfaceFlinger::postFramebuffer()
2210{
Mathias Agopian841cde52012-03-01 15:44:37 -08002211 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002212 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002213
Mathias Agopiana44b0412011-10-16 18:46:35 -07002214 const nsecs_t now = systemTime();
2215 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002216
Dan Stoza9e56aa02015-11-02 13:00:03 -08002217 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2218 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002219 if (!displayDevice->isDisplayOn()) {
2220 continue;
2221 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002222 const auto hwcId = displayDevice->getHwcDisplayId();
2223 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002224 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002225 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002226 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002227 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002228 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002229 // The layer buffer from the previous frame (if any) is released
2230 // by HWC only when the release fence from this frame (if any) is
2231 // signaled. Always get the release fence from HWC first.
2232 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002233 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002234
2235 // If the layer was client composited in the previous frame, we
2236 // need to merge with the previous client target acquire fence.
2237 // Since we do not track that, always merge with the current
2238 // client target acquire fence when it is available, even though
2239 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002240 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002241 releaseFence = Fence::merge("LayerRelease", releaseFence,
2242 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002243 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002244
David Sodmanb8af7922017-12-21 15:17:55 -08002245 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002246 }
Chia-I Wu83806892017-11-16 10:50:20 -08002247
2248 // We've got a list of layers needing fences, that are disjoint with
2249 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2250 // supply them with the present fence.
2251 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002252 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002253 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002254 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002255 }
2256 }
2257
Dan Stoza9e56aa02015-11-02 13:00:03 -08002258 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002259 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002260 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002261 }
2262
Mathias Agopiana44b0412011-10-16 18:46:35 -07002263 mLastSwapBufferTime = systemTime() - now;
2264 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002265
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002266 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002267 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2268 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2269 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2270 logFrameStats();
2271 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002272 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002273}
2274
Mathias Agopian87baae12012-07-31 12:38:26 -07002275void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002276{
Mathias Agopian841cde52012-03-01 15:44:37 -08002277 ATRACE_CALL();
2278
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002279 // here we keep a copy of the drawing state (that is the state that's
2280 // going to be overwritten by handleTransactionLocked()) outside of
2281 // mStateLock so that the side-effects of the State assignment
2282 // don't happen with mStateLock held (which can cause deadlocks).
2283 State drawingState(mDrawingState);
2284
Mathias Agopianca4d3602011-05-19 15:38:14 -07002285 Mutex::Autolock _l(mStateLock);
2286 const nsecs_t now = systemTime();
2287 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002288
Mathias Agopianca4d3602011-05-19 15:38:14 -07002289 // Here we're guaranteed that some transaction flags are set
2290 // so we can call handleTransactionLocked() unconditionally.
2291 // We call getTransactionFlags(), which will also clear the flags,
2292 // with mStateLock held to guarantee that mCurrentState won't change
2293 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002294
Mathias Agopiane57f2922012-08-09 16:29:12 -07002295 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002296 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002297
Mathias Agopianca4d3602011-05-19 15:38:14 -07002298 mLastTransactionTime = systemTime() - now;
2299 mDebugInTransaction = 0;
2300 invalidateHwcGeometry();
2301 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002302}
2303
Lloyd Pique715a2c12017-12-14 17:18:08 -08002304DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002305 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002306 // Figure out whether the event is for the primary display or an
2307 // external display by matching the Hwc display id against one for a
2308 // connected display. If we did not find a match, we then check what
2309 // displays are not already connected to determine the type. If we don't
2310 // have a connected primary display, we assume the new display is meant to
2311 // be the primary display, and then if we don't have an external display,
2312 // we assume it is that.
2313 const auto primaryDisplayId =
2314 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2315 const auto externalDisplayId =
2316 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2317 if (primaryDisplayId && primaryDisplayId == display) {
2318 return DisplayDevice::DISPLAY_PRIMARY;
2319 } else if (externalDisplayId && externalDisplayId == display) {
2320 return DisplayDevice::DISPLAY_EXTERNAL;
2321 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2322 return DisplayDevice::DISPLAY_PRIMARY;
2323 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2324 return DisplayDevice::DISPLAY_EXTERNAL;
2325 }
2326
2327 return DisplayDevice::DISPLAY_ID_INVALID;
2328}
2329
Lloyd Piqueba04e622017-12-14 17:11:26 -08002330void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2331 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002332 auto displayType = determineDisplayType(event.display, event.connection);
2333 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2334 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2335 continue;
2336 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002337
2338 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2339 ALOGE("External displays are not supported by the vr hardware composer.");
2340 continue;
2341 }
2342
Lloyd Pique715a2c12017-12-14 17:18:08 -08002343 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002344
2345 if (event.connection == HWC2::Connection::Connected) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002346 if (!mBuiltinDisplays[displayType].get()) {
2347 ALOGV("Creating built in display %d", displayType);
2348 mBuiltinDisplays[displayType] = new BBinder();
2349 // All non-virtual displays are currently considered secure.
2350 DisplayDeviceState info(displayType, true);
2351 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2352 "Built-in Screen" : "External Screen";
2353 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
2354 mInterceptor->saveDisplayCreation(info);
2355 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002356 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002357 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002358
Lloyd Piquefcd86612017-12-14 17:15:36 -08002359 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2360 if (idx >= 0) {
2361 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Lloyd Pique4dccc412018-01-22 17:21:36 -08002362 mInterceptor->saveDisplayDeletion(info.displayId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002363 mCurrentState.displays.removeItemsAt(idx);
2364 }
2365 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002366 }
2367
2368 processDisplayChangesLocked();
2369 }
2370
2371 mPendingHotplugEvents.clear();
2372}
2373
Lloyd Pique99d3da52018-01-22 17:48:03 -08002374sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2375 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2376 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
2377 bool hasWideColorSupport = false;
2378 if (hasWideColorDisplay) {
2379 std::vector<ColorMode> modes = getHwComposer().getColorModes(state.type);
2380 for (ColorMode colorMode : modes) {
2381 switch (colorMode) {
2382 case ColorMode::DISPLAY_P3:
2383 case ColorMode::ADOBE_RGB:
2384 case ColorMode::DCI_P3:
2385 hasWideColorSupport = true;
2386 break;
2387 default:
2388 break;
2389 }
2390 }
2391 }
2392
2393 bool hasHdrSupport = false;
2394 std::unique_ptr<HdrCapabilities> hdrCapabilities =
2395 getHwComposer().getHdrCapabilities(state.type);
2396 if (hdrCapabilities) {
2397 const std::vector<int32_t> types = hdrCapabilities->getSupportedHdrTypes();
2398 auto iter = std::find(types.cbegin(), types.cend(), HAL_HDR_HDR10);
2399 hasHdrSupport = iter != types.cend();
2400 }
2401
2402 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2403 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2404
2405 /*
2406 * Create our display's surface
2407 */
2408 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2409 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
2410 renderSurface->setAsync(state.type >= DisplayDevice::DISPLAY_VIRTUAL);
2411 renderSurface->setNativeWindow(nativeWindow.get());
2412 const int displayWidth = renderSurface->queryWidth();
2413 const int displayHeight = renderSurface->queryHeight();
2414
2415 // Make sure that composition can never be stalled by a virtual display
2416 // consumer that isn't processing buffers fast enough. We have to do this
2417 // in two places:
2418 // * Here, in case the display is composed entirely by HWC.
2419 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2420 // window's swap interval in eglMakeCurrent, so they'll override the
2421 // interval we set here.
2422 if (state.type >= DisplayDevice::DISPLAY_VIRTUAL) {
2423 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2424 }
2425
2426 // virtual displays are always considered enabled
2427 auto initialPowerMode = (state.type >= DisplayDevice::DISPLAY_VIRTUAL) ? HWC_POWER_MODE_NORMAL
2428 : HWC_POWER_MODE_OFF;
2429
2430 sp<DisplayDevice> hw =
2431 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2432 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
2433 hasWideColorSupport, hasHdrSupport, initialPowerMode);
2434
2435 if (maxFrameBufferAcquiredBuffers >= 3) {
2436 nativeWindowSurface->preallocateBuffers();
2437 }
2438
2439 ColorMode defaultColorMode = ColorMode::NATIVE;
2440 if (hasWideColorSupport) {
2441 defaultColorMode = ColorMode::SRGB;
2442 }
2443 setActiveColorModeInternal(hw, defaultColorMode);
2444 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
2445 hw->setLayerStack(state.layerStack);
2446 hw->setProjection(state.orientation, state.viewport, state.frame);
2447 hw->setDisplayName(state.displayName);
2448
2449 return hw;
2450}
2451
Lloyd Pique347200f2017-12-14 17:00:15 -08002452void SurfaceFlinger::processDisplayChangesLocked() {
2453 // here we take advantage of Vector's copy-on-write semantics to
2454 // improve performance by skipping the transaction entirely when
2455 // know that the lists are identical
2456 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2457 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2458 if (!curr.isIdenticalTo(draw)) {
2459 mVisibleRegionsDirty = true;
2460 const size_t cc = curr.size();
2461 size_t dc = draw.size();
2462
2463 // find the displays that were removed
2464 // (ie: in drawing state but not in current state)
2465 // also handle displays that changed
2466 // (ie: displays that are in both lists)
2467 for (size_t i = 0; i < dc;) {
2468 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2469 if (j < 0) {
2470 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002471 // Call makeCurrent() on the primary display so we can
2472 // be sure that nothing associated with this display
2473 // is current.
2474 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2475 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2476 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2477 if (hw != nullptr) hw->disconnect(getHwComposer());
2478 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2479 mEventThread->onHotplugReceived(draw[i].type, false);
2480 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002481 } else {
2482 // this display is in both lists. see if something changed.
2483 const DisplayDeviceState& state(curr[j]);
2484 const wp<IBinder>& display(curr.keyAt(j));
2485 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2486 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2487 if (state_binder != draw_binder) {
2488 // changing the surface is like destroying and
2489 // recreating the DisplayDevice, so we just remove it
2490 // from the drawing state, so that it get re-added
2491 // below.
2492 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2493 if (hw != nullptr) hw->disconnect(getHwComposer());
2494 mDisplays.removeItem(display);
2495 mDrawingState.displays.removeItemsAt(i);
2496 dc--;
2497 // at this point we must loop to the next item
2498 continue;
2499 }
2500
2501 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2502 if (disp != nullptr) {
2503 if (state.layerStack != draw[i].layerStack) {
2504 disp->setLayerStack(state.layerStack);
2505 }
2506 if ((state.orientation != draw[i].orientation) ||
2507 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2508 disp->setProjection(state.orientation, state.viewport, state.frame);
2509 }
2510 if (state.width != draw[i].width || state.height != draw[i].height) {
2511 disp->setDisplaySize(state.width, state.height);
2512 }
2513 }
2514 }
2515 ++i;
2516 }
2517
2518 // find displays that were added
2519 // (ie: in current state but not in drawing state)
2520 for (size_t i = 0; i < cc; i++) {
2521 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2522 const DisplayDeviceState& state(curr[i]);
2523
2524 sp<DisplaySurface> dispSurface;
2525 sp<IGraphicBufferProducer> producer;
2526 sp<IGraphicBufferProducer> bqProducer;
2527 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002528 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002529
2530 int32_t hwcId = -1;
2531 if (state.isVirtualDisplay()) {
2532 // Virtual displays without a surface are dormant:
2533 // they have external state (layer stack, projection,
2534 // etc.) but no internal state (i.e. a DisplayDevice).
2535 if (state.surface != nullptr) {
2536 // Allow VR composer to use virtual displays.
2537 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2538 int width = 0;
2539 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2540 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2541 int height = 0;
2542 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2543 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2544 int intFormat = 0;
2545 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2546 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2547 auto format = static_cast<android_pixel_format_t>(intFormat);
2548
2549 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2550 }
2551
2552 // TODO: Plumb requested format back up to consumer
2553
2554 sp<VirtualDisplaySurface> vds =
2555 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2556 bqProducer, bqConsumer,
2557 state.displayName);
2558
2559 dispSurface = vds;
2560 producer = vds;
2561 }
2562 } else {
2563 ALOGE_IF(state.surface != nullptr,
2564 "adding a supported display, but rendering "
2565 "surface is provided (%p), ignoring it",
2566 state.surface.get());
2567
2568 hwcId = state.type;
2569 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2570 producer = bqProducer;
2571 }
2572
2573 const wp<IBinder>& display(curr.keyAt(i));
2574 if (dispSurface != nullptr) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002575 mDisplays.add(display,
2576 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2577 producer));
Lloyd Pique347200f2017-12-14 17:00:15 -08002578 if (!state.isVirtualDisplay()) {
2579 mEventThread->onHotplugReceived(state.type, true);
2580 }
2581 }
2582 }
2583 }
2584 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002585
2586 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002587}
2588
Mathias Agopian87baae12012-07-31 12:38:26 -07002589void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002590{
Dan Stoza7dde5992015-05-22 09:51:44 -07002591 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002592 mCurrentState.traverseInZOrder([](Layer* layer) {
2593 layer->notifyAvailableFrames();
2594 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002595
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002596 /*
2597 * Traversal of the children
2598 * (perform the transaction for each of them if needed)
2599 */
2600
Mathias Agopian3559b072012-08-15 13:46:03 -07002601 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002602 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002603 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002604 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002605
2606 const uint32_t flags = layer->doTransaction(0);
2607 if (flags & Layer::eVisibleRegion)
2608 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002609 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002610 }
2611
2612 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002613 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002614 */
2615
Mathias Agopiane57f2922012-08-09 16:29:12 -07002616 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002617 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002618 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002619 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002620
Mathias Agopian84300952012-11-21 16:02:13 -08002621 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2622 // The transform hint might have changed for some layers
2623 // (either because a display has changed, or because a layer
2624 // as changed).
2625 //
2626 // Walk through all the layers in currentLayers,
2627 // and update their transform hint.
2628 //
2629 // If a layer is visible only on a single display, then that
2630 // display is used to calculate the hint, otherwise we use the
2631 // default display.
2632 //
2633 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2634 // the hint is set before we acquire a buffer from the surface texture.
2635 //
2636 // NOTE: layer transactions have taken place already, so we use their
2637 // drawing state. However, SurfaceFlinger's own transaction has not
2638 // happened yet, so we must use the current state layer list
2639 // (soon to become the drawing state list).
2640 //
2641 sp<const DisplayDevice> disp;
2642 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002643 bool first = true;
2644 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002645 // NOTE: we rely on the fact that layers are sorted by
2646 // layerStack first (so we don't have to traverse the list
2647 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002648 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002649 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002650 currentlayerStack = layerStack;
2651 // figure out if this layerstack is mirrored
2652 // (more than one display) if so, pick the default display,
2653 // if not, pick the only display it's on.
2654 disp.clear();
2655 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2656 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002657 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002658 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002659 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002660 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002661 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002662 break;
2663 }
2664 }
2665 }
2666 }
Chet Haase91d25932013-04-11 15:24:55 -07002667
Robert Carr56a0b9a2017-12-04 16:06:13 -08002668 if (transactionFlags & eDisplayTransactionNeeded) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002669 if (disp == nullptr) {
Robert Carr56a0b9a2017-12-04 16:06:13 -08002670 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2671 // redraw after transform hint changes. See bug 8508397.
2672
2673 // could be null when this layer is using a layerStack
2674 // that is not visible on any display. Also can occur at
2675 // screen off/on times.
2676 disp = getDefaultDisplayDeviceLocked();
2677 }
2678 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08002679 }
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002680 if (disp != nullptr) {
2681 layer->updateTransformHint(disp);
2682 }
Robert Carr2047fae2016-11-28 14:09:09 -08002683
2684 first = false;
2685 });
Mathias Agopian84300952012-11-21 16:02:13 -08002686 }
2687
2688
Mathias Agopian3559b072012-08-15 13:46:03 -07002689 /*
2690 * Perform our own transaction if needed
2691 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002692
2693 if (mLayersAdded) {
2694 mLayersAdded = false;
2695 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002696 mVisibleRegionsDirty = true;
2697 }
2698
2699 // some layers might have been removed, so
2700 // we need to update the regions they're exposing.
2701 if (mLayersRemoved) {
2702 mLayersRemoved = false;
2703 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002704 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002705 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002706 // this layer is not visible anymore
2707 // TODO: we could traverse the tree from front to back and
2708 // compute the actual visible region
2709 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002710 Region visibleReg;
2711 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002712 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002713 }
Robert Carr2047fae2016-11-28 14:09:09 -08002714 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002715 }
2716
2717 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002718
2719 updateCursorAsync();
2720}
2721
2722void SurfaceFlinger::updateCursorAsync()
2723{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002724 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2725 auto& displayDevice = mDisplays[displayId];
2726 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002727 continue;
2728 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002729
2730 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2731 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002732 }
2733 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002734}
2735
2736void SurfaceFlinger::commitTransaction()
2737{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002738 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002739 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002740 for (const auto& l : mLayersPendingRemoval) {
2741 recordBufferingStats(l->getName().string(),
2742 l->getOccupancyHistory(true));
2743 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002744 }
2745 mLayersPendingRemoval.clear();
2746 }
2747
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002748 // If this transaction is part of a window animation then the next frame
2749 // we composite should be considered an animation as well.
2750 mAnimCompositionPending = mAnimTransactionPending;
2751
Mathias Agopian4fec8732012-06-29 14:12:52 -07002752 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002753 mDrawingState.traverseInZOrder([](Layer* layer) {
2754 layer->commitChildList();
2755 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002756 mTransactionPending = false;
2757 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002758 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002759}
2760
Chia-I Wuab0c3192017-08-01 11:29:00 -07002761void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002762 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002763{
Mathias Agopian841cde52012-03-01 15:44:37 -08002764 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002765 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002766
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002767 Region aboveOpaqueLayers;
2768 Region aboveCoveredLayers;
2769 Region dirty;
2770
Mathias Agopian87baae12012-07-31 12:38:26 -07002771 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002772
Robert Carr2047fae2016-11-28 14:09:09 -08002773 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002774 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002775 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002776
Jesse Hall01e29052013-02-19 16:13:35 -08002777 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002778 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002779 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002780
Mathias Agopianab028732010-03-16 16:41:46 -07002781 /*
2782 * opaqueRegion: area of a surface that is fully opaque.
2783 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002784 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002785
2786 /*
2787 * visibleRegion: area of a surface that is visible on screen
2788 * and not fully transparent. This is essentially the layer's
2789 * footprint minus the opaque regions above it.
2790 * Areas covered by a translucent surface are considered visible.
2791 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002792 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002793
2794 /*
2795 * coveredRegion: area of a surface that is covered by all
2796 * visible regions above it (which includes the translucent areas).
2797 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002798 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002799
Jesse Halla8026d22012-09-25 13:25:04 -07002800 /*
2801 * transparentRegion: area of a surface that is hinted to be completely
2802 * transparent. This is only used to tell when the layer has no visible
2803 * non-transparent regions and can be removed from the layer list. It
2804 * does not affect the visibleRegion of this layer or any layers
2805 * beneath it. The hint may not be correct if apps don't respect the
2806 * SurfaceView restrictions (which, sadly, some don't).
2807 */
2808 Region transparentRegion;
2809
Mathias Agopianab028732010-03-16 16:41:46 -07002810
2811 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002812 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002813 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002814 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002815 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002816 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002817 if (!visibleRegion.isEmpty()) {
2818 // Remove the transparent area from the visible region
2819 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002820 if (tr.preserveRects()) {
2821 // transform the transparent region
2822 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002823 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002824 // transformation too complex, can't do the
2825 // transparent region optimization.
2826 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002827 }
Mathias Agopianab028732010-03-16 16:41:46 -07002828 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002829
Mathias Agopianab028732010-03-16 16:41:46 -07002830 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002831 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002832 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002833 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2834 // the opaque region is the layer's footprint
2835 opaqueRegion = visibleRegion;
2836 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002837 }
2838 }
2839
Robert Carre5f4f692018-01-12 13:12:28 -08002840 if (visibleRegion.isEmpty()) {
2841 layer->clearVisibilityRegions();
2842 return;
2843 }
2844
Mathias Agopianab028732010-03-16 16:41:46 -07002845 // Clip the covered region to the visible region
2846 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2847
2848 // Update aboveCoveredLayers for next (lower) layer
2849 aboveCoveredLayers.orSelf(visibleRegion);
2850
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002851 // subtract the opaque region covered by the layers above us
2852 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002853
2854 // compute this layer's dirty region
2855 if (layer->contentDirty) {
2856 // we need to invalidate the whole region
2857 dirty = visibleRegion;
2858 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002859 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002860 layer->contentDirty = false;
2861 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002862 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002863 * the exposed region consists of two components:
2864 * 1) what's VISIBLE now and was COVERED before
2865 * 2) what's EXPOSED now less what was EXPOSED before
2866 *
2867 * note that (1) is conservative, we start with the whole
2868 * visible region but only keep what used to be covered by
2869 * something -- which mean it may have been exposed.
2870 *
2871 * (2) handles areas that were not covered by anything but got
2872 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002873 */
Mathias Agopianab028732010-03-16 16:41:46 -07002874 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002875 const Region oldVisibleRegion = layer->visibleRegion;
2876 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002877 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2878 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002879 }
2880 dirty.subtractSelf(aboveOpaqueLayers);
2881
2882 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002883 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002884
Mathias Agopianab028732010-03-16 16:41:46 -07002885 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002886 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002887
Jesse Halla8026d22012-09-25 13:25:04 -07002888 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002889 layer->setVisibleRegion(visibleRegion);
2890 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002891 layer->setVisibleNonTransparentRegion(
2892 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002893 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002894
Mathias Agopian87baae12012-07-31 12:38:26 -07002895 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002896}
2897
Chia-I Wuab0c3192017-08-01 11:29:00 -07002898void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002899 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002900 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002901 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002902 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002903 }
2904 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002905}
2906
Dan Stoza6b9454d2014-11-07 16:00:59 -08002907bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002908{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002909 ALOGV("handlePageFlip");
2910
Brian Andersond6927fb2016-07-23 23:37:30 -07002911 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002912
Mathias Agopian4fec8732012-06-29 14:12:52 -07002913 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002914 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002915 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002916
2917 // Store the set of layers that need updates. This set must not change as
2918 // buffers are being latched, as this could result in a deadlock.
2919 // Example: Two producers share the same command stream and:
2920 // 1.) Layer 0 is latched
2921 // 2.) Layer 0 gets a new frame
2922 // 2.) Layer 1 gets a new frame
2923 // 3.) Layer 1 is latched.
2924 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2925 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002926 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002927 if (layer->hasQueuedFrame()) {
2928 frameQueued = true;
2929 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002930 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002931 } else {
2932 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002933 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002934 } else {
2935 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002936 }
Robert Carr2047fae2016-11-28 14:09:09 -08002937 });
2938
Dan Stoza9e56aa02015-11-02 13:00:03 -08002939 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002940 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002941 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002942 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002943 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002944 newDataLatched = true;
2945 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002946 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002947
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002948 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002949
2950 // If we will need to wake up at some time in the future to deal with a
2951 // queued frame that shouldn't be displayed during this vsync period, wake
2952 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002953 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002954 signalLayerUpdate();
2955 }
2956
2957 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002958 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002959}
2960
Mathias Agopianad456f92011-01-13 17:53:01 -08002961void SurfaceFlinger::invalidateHwcGeometry()
2962{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002963 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002964}
2965
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002966
Fabien Sanglard830b8472016-11-30 16:35:58 -08002967void SurfaceFlinger::doDisplayComposition(
2968 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002969 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002970{
Dan Stoza71433162014-02-04 16:22:36 -08002971 // We only need to actually compose the display if:
2972 // 1) It is being handled by hardware composer, which may need this to
2973 // keep its virtual display state machine in sync, or
2974 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002975 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002976 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002977 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002978 return;
2979 }
2980
Dan Stoza9e56aa02015-11-02 13:00:03 -08002981 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002982 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002983
2984 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002985 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002986}
2987
Chia-I Wub02087d2017-11-09 10:19:54 -08002988bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002989{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002990 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002991
Chia-I Wub02087d2017-11-09 10:19:54 -08002992 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002993 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002994 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002995
2996 mat4 oldColorMatrix;
David Sodman105b7dc2017-11-04 20:28:14 -07002997 const bool applyColorMatrix = !getBE().mHwc->hasDeviceComposition(hwcId) &&
2998 !getBE().mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002999 if (applyColorMatrix) {
3000 mat4 colorMatrix = mColorMatrix * mDaltonizer();
3001 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
3002 }
3003
David Sodman105b7dc2017-11-04 20:28:14 -07003004 bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
David Sodman4b7c4bc2017-11-17 12:13:59 -08003005 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003006 if (hasClientComposition) {
3007 ALOGV("hasClientComposition");
3008
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003009 android_dataspace outputDataspace = HAL_DATASPACE_UNKNOWN;
Chia-I Wu9a48a8c2018-02-20 14:27:30 -08003010 if (displayDevice->getWideColorSupport() &&
Peiyong Lina52f0292018-03-14 17:26:31 -07003011 displayDevice->getActiveColorMode() == ColorMode::DISPLAY_P3) {
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003012 outputDataspace = HAL_DATASPACE_DISPLAY_P3;
3013 }
3014 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
3015
Chia-I Wu7f402902017-11-09 12:51:10 -08003016 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003017 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003018 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08003019 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003020
3021 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08003022 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07003023 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
3024 }
3025 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003026 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003027
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003028 // Never touch the framebuffer if we don't have any framebuffer layers
David Sodman105b7dc2017-11-04 20:28:14 -07003029 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003030 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003031 // when using overlays, we assume a fully transparent framebuffer
3032 // NOTE: we could reduce how much we need to clear, for instance
3033 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003034 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003035 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003036 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003037 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003038 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003039 // we're left with the letterbox region
3040 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08003041 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07003042
3043 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08003044 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07003045
Mathias Agopianb9494d52012-04-18 02:28:45 -07003046 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003047 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003048 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08003049 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003050 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003051 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003052
Dan Stoza9e56aa02015-11-02 13:00:03 -08003053 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07003054 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07003055 // scissor on the main display. It should never be needed
3056 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08003057 const Rect& bounds(displayDevice->getBounds());
3058 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003059 if (scissor != bounds) {
3060 // scissor doesn't match the screen's dimensions, so we
3061 // need to clear everything outside of it and enable
3062 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003063
Mathias Agopianf45c5102012-10-24 16:29:17 -07003064 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08003065 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08003066 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07003067 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003068 }
3069 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003070 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003071
Mathias Agopian85d751c2012-08-29 16:59:24 -07003072 /*
3073 * and then, render the layers targeted at the framebuffer
3074 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003075
Dan Stoza9e56aa02015-11-02 13:00:03 -08003076 ALOGV("Rendering client layers");
3077 const Transform& displayTransform = displayDevice->getTransform();
3078 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07003079 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08003080 bool firstLayer = true;
3081 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08003082 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08003083 displayTransform.transform(layer->visibleRegion)));
3084 ALOGV("Layer: %s", layer->getName().string());
3085 ALOGV(" Composition type: %s",
3086 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07003087 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003088 switch (layer->getCompositionType(hwcId)) {
3089 case HWC2::Composition::Cursor:
3090 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08003091 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08003092 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07003093 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003094 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07003095 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08003096 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07003097 // never clear the very first layer since we're
3098 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07003099 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003100 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003101 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003102 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003103 case HWC2::Composition::Client: {
chaviwa76b2712017-09-20 12:02:26 -07003104 layer->draw(renderArea, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07003105 break;
3106 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003107 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07003108 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003109 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003110 } else {
3111 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003112 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003113 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003114 }
3115 } else {
3116 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08003117 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08003118 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08003119 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07003120 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07003121 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07003122 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003123 }
3124 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003125
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003126 if (applyColorMatrix) {
3127 getRenderEngine().setupColorTransform(oldColorMatrix);
3128 }
3129
Mathias Agopianf45c5102012-10-24 16:29:17 -07003130 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003131 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003132 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003133}
3134
Fabien Sanglard830b8472016-11-30 16:35:58 -08003135void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
3136 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003137 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003138 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003139}
3140
Dan Stoza7d89d062015-04-30 13:29:25 -07003141status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003142 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003143 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003144 const sp<Layer>& lbc,
3145 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003146{
Dan Stoza7d89d062015-04-30 13:29:25 -07003147 // add this layer to the current state list
3148 {
3149 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003150 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003151 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3152 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003153 return NO_MEMORY;
3154 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003155 if (parent == nullptr) {
3156 mCurrentState.layersSortedByZ.add(lbc);
3157 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003158 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003159 ALOGE("addClientLayer called with a removed parent");
3160 return NAME_NOT_FOUND;
3161 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003162 parent->addChild(lbc);
3163 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003164
Dan Stoza101d8dc2018-02-27 15:42:25 -08003165 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
Dan Stoza0a0158c2018-03-16 13:38:54 -07003166 // TODO (b/74616334): Change this back to a fatal assert once the leak is fixed
3167 ALOGE_IF(mGraphicBufferProducerList.size() > mMaxGraphicBufferProducerListSize,
3168 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3169 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize,
3170 mNumLayers);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003171 mLayersAdded = true;
3172 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003173 }
3174
Mathias Agopian96f08192010-06-02 23:28:45 -07003175 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003176 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003177
Dan Stoza7d89d062015-04-30 13:29:25 -07003178 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003179}
3180
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003181status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003182 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003183 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3184}
Robert Carr7f9b8992017-03-10 11:08:39 -08003185
chaviwca27f252018-02-06 16:46:39 -08003186status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3187 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003188 if (layer->isPendingRemoval()) {
3189 return NO_ERROR;
3190 }
3191
Robert Carr1f0a16a2016-10-24 16:27:39 -07003192 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003193 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003194 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003195 if (topLevelOnly) {
3196 return NO_ERROR;
3197 }
3198
Chia-I Wu98f1c102017-05-30 14:54:08 -07003199 sp<Layer> ancestor = p;
3200 while (ancestor->getParent() != nullptr) {
3201 ancestor = ancestor->getParent();
3202 }
3203 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3204 ALOGE("removeLayer called with a layer whose parent has been removed");
3205 return NAME_NOT_FOUND;
3206 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003207
3208 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003209 } else {
3210 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003211 }
3212
Robert Carr136e2f62017-02-08 17:54:29 -08003213 // As a matter of normal operation, the LayerCleaner will produce a second
3214 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3215 // so we will succeed in promoting it, but it's already been removed
3216 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3217 // otherwise something has gone wrong and we are leaking the layer.
3218 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003219 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3220 layer->getName().string(),
3221 (p != nullptr) ? p->getName().string() : "no-parent");
3222 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003223 } else if (index < 0) {
3224 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003225 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003226
Chia-I Wuc6657022017-08-15 11:18:17 -07003227 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003228 mLayersPendingRemoval.add(layer);
3229 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003230 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003231 setTransactionFlags(eTransactionNeeded);
3232 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003233}
3234
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003235uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003236 return android_atomic_release_load(&mTransactionFlags);
3237}
3238
Mathias Agopian3f844832013-08-07 21:24:32 -07003239uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003240 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3241}
3242
Mathias Agopian3f844832013-08-07 21:24:32 -07003243uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003244 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
3245 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003246 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003247 }
3248 return old;
3249}
3250
chaviwca27f252018-02-06 16:46:39 -08003251bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3252 for (const ComposerState& state : states) {
3253 // Here we need to check that the interface we're given is indeed
3254 // one of our own. A malicious client could give us a nullptr
3255 // IInterface, or one of its own or even one of our own but a
3256 // different type. All these situations would cause us to crash.
3257 if (state.client == nullptr) {
3258 return true;
3259 }
3260
3261 sp<IBinder> binder = IInterface::asBinder(state.client);
3262 if (binder == nullptr) {
3263 return true;
3264 }
3265
3266 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3267 return true;
3268 }
3269 }
3270 return false;
3271}
3272
Mathias Agopian8b33f032012-07-24 20:43:54 -07003273void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003274 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003275 const Vector<DisplayState>& displays,
3276 uint32_t flags)
3277{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003278 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003279 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003280 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003281
chaviwca27f252018-02-06 16:46:39 -08003282 if (containsAnyInvalidClientState(states)) {
3283 return;
3284 }
3285
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003286 if (flags & eAnimation) {
3287 // For window updates that are part of an animation we must wait for
3288 // previous animation "frames" to be handled.
3289 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003290 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003291 if (CC_UNLIKELY(err != NO_ERROR)) {
3292 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003293 // caller after a few seconds.
3294 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3295 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003296 mAnimTransactionPending = false;
3297 break;
3298 }
3299 }
3300 }
3301
chaviwca27f252018-02-06 16:46:39 -08003302 for (const DisplayState& display : displays) {
3303 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003304 }
3305
chaviwca27f252018-02-06 16:46:39 -08003306 for (const ComposerState& state : states) {
3307 transactionFlags |= setClientStateLocked(state);
3308 }
3309
3310 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3311 // as destroyed should only occur after setting all other states. This is to allow for a
3312 // child re-parent to happen before marking its original parent as destroyed (which would
3313 // then mark the child as destroyed).
3314 for (const ComposerState& state : states) {
3315 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003316 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003317
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003318 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3319 // anyway. This can be used as a flush mechanism for previous async transactions.
3320 // Empty animation transaction can be used to simulate back-pressure, so also force a
3321 // transaction for empty animation transactions.
3322 if (transactionFlags == 0 &&
3323 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003324 transactionFlags = eTransactionNeeded;
3325 }
3326
Mathias Agopian386aa982011-11-07 21:58:03 -08003327 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003328 if (mInterceptor->isEnabled()) {
3329 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003330 }
Irvel468051e2016-06-13 16:44:44 -07003331
Mathias Agopian386aa982011-11-07 21:58:03 -08003332 // this triggers the transaction
3333 setTransactionFlags(transactionFlags);
3334
3335 // if this is a synchronous transaction, wait for it to take effect
3336 // before returning.
3337 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003338 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003339 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003340 if (flags & eAnimation) {
3341 mAnimTransactionPending = true;
3342 }
3343 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003344 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3345 if (CC_UNLIKELY(err != NO_ERROR)) {
3346 // just in case something goes wrong in SF, return to the
3347 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003348 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3349 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003350 break;
3351 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003352 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003353 }
3354}
3355
Mathias Agopiane57f2922012-08-09 16:29:12 -07003356uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3357{
Jesse Hall9a143922012-10-04 16:29:19 -07003358 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3359 if (dpyIdx < 0)
3360 return 0;
3361
Mathias Agopiane57f2922012-08-09 16:29:12 -07003362 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003363 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003364 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003365 const uint32_t what = s.what;
3366 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003367 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003368 disp.surface = s.surface;
3369 flags |= eDisplayTransactionNeeded;
3370 }
3371 }
3372 if (what & DisplayState::eLayerStackChanged) {
3373 if (disp.layerStack != s.layerStack) {
3374 disp.layerStack = s.layerStack;
3375 flags |= eDisplayTransactionNeeded;
3376 }
3377 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003378 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003379 if (disp.orientation != s.orientation) {
3380 disp.orientation = s.orientation;
3381 flags |= eDisplayTransactionNeeded;
3382 }
3383 if (disp.frame != s.frame) {
3384 disp.frame = s.frame;
3385 flags |= eDisplayTransactionNeeded;
3386 }
3387 if (disp.viewport != s.viewport) {
3388 disp.viewport = s.viewport;
3389 flags |= eDisplayTransactionNeeded;
3390 }
3391 }
Michael Lentine47e45402014-07-18 15:34:25 -07003392 if (what & DisplayState::eDisplaySizeChanged) {
3393 if (disp.width != s.width) {
3394 disp.width = s.width;
3395 flags |= eDisplayTransactionNeeded;
3396 }
3397 if (disp.height != s.height) {
3398 disp.height = s.height;
3399 flags |= eDisplayTransactionNeeded;
3400 }
3401 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003402 }
3403 return flags;
3404}
3405
chaviwca27f252018-02-06 16:46:39 -08003406uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3407 const layer_state_t& s = composerState.state;
3408 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3409
Mathias Agopian13127d82013-03-05 17:47:11 -08003410 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003411 if (layer == nullptr) {
3412 return 0;
3413 }
3414
3415 if (layer->isPendingRemoval()) {
3416 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3417 return 0;
3418 }
3419
3420 uint32_t flags = 0;
3421
3422 const uint32_t what = s.what;
3423 bool geometryAppliesWithResize =
3424 what & layer_state_t::eGeometryAppliesWithResize;
3425 if (what & layer_state_t::ePositionChanged) {
3426 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3427 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003428 }
chaviw8b3871a2017-11-01 17:41:01 -07003429 }
3430 if (what & layer_state_t::eLayerChanged) {
3431 // NOTE: index needs to be calculated before we update the state
3432 const auto& p = layer->getParent();
3433 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003434 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003435 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003436 mCurrentState.layersSortedByZ.removeAt(idx);
3437 mCurrentState.layersSortedByZ.add(layer);
3438 // we need traversal (state changed)
3439 // AND transaction (list changed)
3440 flags |= eTransactionNeeded|eTraversalNeeded;
3441 }
chaviw8b3871a2017-11-01 17:41:01 -07003442 } else {
3443 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003444 flags |= eTransactionNeeded|eTraversalNeeded;
3445 }
3446 }
chaviw8b3871a2017-11-01 17:41:01 -07003447 }
3448 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003449 // NOTE: index needs to be calculated before we update the state
3450 const auto& p = layer->getParent();
3451 if (p == nullptr) {
3452 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3453 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3454 mCurrentState.layersSortedByZ.removeAt(idx);
3455 mCurrentState.layersSortedByZ.add(layer);
3456 // we need traversal (state changed)
3457 // AND transaction (list changed)
3458 flags |= eTransactionNeeded|eTraversalNeeded;
3459 }
3460 } else {
3461 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3462 flags |= eTransactionNeeded|eTraversalNeeded;
3463 }
chaviw8b3871a2017-11-01 17:41:01 -07003464 }
3465 }
3466 if (what & layer_state_t::eSizeChanged) {
3467 if (layer->setSize(s.w, s.h)) {
3468 flags |= eTraversalNeeded;
3469 }
3470 }
3471 if (what & layer_state_t::eAlphaChanged) {
3472 if (layer->setAlpha(s.alpha))
3473 flags |= eTraversalNeeded;
3474 }
3475 if (what & layer_state_t::eColorChanged) {
3476 if (layer->setColor(s.color))
3477 flags |= eTraversalNeeded;
3478 }
3479 if (what & layer_state_t::eMatrixChanged) {
3480 if (layer->setMatrix(s.matrix))
3481 flags |= eTraversalNeeded;
3482 }
3483 if (what & layer_state_t::eTransparentRegionChanged) {
3484 if (layer->setTransparentRegionHint(s.transparentRegion))
3485 flags |= eTraversalNeeded;
3486 }
3487 if (what & layer_state_t::eFlagsChanged) {
3488 if (layer->setFlags(s.flags, s.mask))
3489 flags |= eTraversalNeeded;
3490 }
3491 if (what & layer_state_t::eCropChanged) {
3492 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3493 flags |= eTraversalNeeded;
3494 }
3495 if (what & layer_state_t::eFinalCropChanged) {
3496 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3497 flags |= eTraversalNeeded;
3498 }
3499 if (what & layer_state_t::eLayerStackChanged) {
3500 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3501 // We only allow setting layer stacks for top level layers,
3502 // everything else inherits layer stack from its parent.
3503 if (layer->hasParent()) {
3504 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3505 layer->getName().string());
3506 } else if (idx < 0) {
3507 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3508 "that also does not appear in the top level layer list. Something"
3509 " has gone wrong.", layer->getName().string());
3510 } else if (layer->setLayerStack(s.layerStack)) {
3511 mCurrentState.layersSortedByZ.removeAt(idx);
3512 mCurrentState.layersSortedByZ.add(layer);
3513 // we need traversal (state changed)
3514 // AND transaction (list changed)
3515 flags |= eTransactionNeeded|eTraversalNeeded;
3516 }
3517 }
3518 if (what & layer_state_t::eDeferTransaction) {
3519 if (s.barrierHandle != nullptr) {
3520 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3521 } else if (s.barrierGbp != nullptr) {
3522 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3523 if (authenticateSurfaceTextureLocked(gbp)) {
3524 const auto& otherLayer =
3525 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3526 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3527 } else {
3528 ALOGE("Attempt to defer transaction to to an"
3529 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003530 }
3531 }
chaviw8b3871a2017-11-01 17:41:01 -07003532 // We don't trigger a traversal here because if no other state is
3533 // changed, we don't want this to cause any more work
3534 }
3535 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003536 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003537 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003538 if (!hadParent) {
3539 mCurrentState.layersSortedByZ.remove(layer);
3540 }
chaviw8b3871a2017-11-01 17:41:01 -07003541 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003542 }
chaviw8b3871a2017-11-01 17:41:01 -07003543 }
3544 if (what & layer_state_t::eReparentChildren) {
3545 if (layer->reparentChildren(s.reparentHandle)) {
3546 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003547 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003548 }
chaviw8b3871a2017-11-01 17:41:01 -07003549 if (what & layer_state_t::eDetachChildren) {
3550 layer->detachChildren();
3551 }
3552 if (what & layer_state_t::eOverrideScalingModeChanged) {
3553 layer->setOverrideScalingMode(s.overrideScalingMode);
3554 // We don't trigger a traversal here because if no other state is
3555 // changed, we don't want this to cause any more work
3556 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003557 return flags;
3558}
3559
chaviwca27f252018-02-06 16:46:39 -08003560void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3561 const layer_state_t& state = composerState.state;
3562 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3563
3564 sp<Layer> layer(client->getLayerUser(state.surface));
3565 if (layer == nullptr) {
3566 return;
3567 }
3568
3569 if (layer->isPendingRemoval()) {
3570 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3571 return;
3572 }
3573
3574 if (state.what & layer_state_t::eDestroySurface) {
3575 removeLayerLocked(mStateLock, layer);
3576 }
3577}
3578
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003579status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003580 const String8& name,
3581 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003582 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003583 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003584 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003585{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003586 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003587 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003588 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003589 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003590 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003591
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003592 status_t result = NO_ERROR;
3593
3594 sp<Layer> layer;
3595
Cody Northropbc755282017-03-31 12:00:08 -06003596 String8 uniqueName = getUniqueLayerName(name);
3597
Mathias Agopian3165cc22012-08-08 19:42:09 -07003598 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3599 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003600 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003601 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003602 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003603
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003604 break;
chaviw13fdc492017-06-27 12:40:18 -07003605 case ISurfaceComposerClient::eFXSurfaceColor:
3606 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003607 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003608 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003609 break;
3610 default:
3611 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003612 break;
3613 }
3614
Dan Stoza7d89d062015-04-30 13:29:25 -07003615 if (result != NO_ERROR) {
3616 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003617 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003618
Chia-I Wuab0c3192017-08-01 11:29:00 -07003619 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3620 // TODO b/64227542
3621 if (windowType == 441731) {
3622 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3623 layer->setPrimaryDisplayOnly();
3624 }
3625
Albert Chaulk479c60c2017-01-27 14:21:34 -05003626 layer->setInfo(windowType, ownerUid);
3627
Robert Carr1f0a16a2016-10-24 16:27:39 -07003628 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003629 if (result != NO_ERROR) {
3630 return result;
3631 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003632 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003633
3634 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003635 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003636}
3637
Cody Northropbc755282017-03-31 12:00:08 -06003638String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3639{
3640 bool matchFound = true;
3641 uint32_t dupeCounter = 0;
3642
3643 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3644 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3645
3646 // Loop over layers until we're sure there is no matching name
3647 while (matchFound) {
3648 matchFound = false;
3649 mDrawingState.traverseInZOrder([&](Layer* layer) {
3650 if (layer->getName() == uniqueName) {
3651 matchFound = true;
3652 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3653 }
3654 });
3655 }
3656
3657 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3658
3659 return uniqueName;
3660}
3661
David Sodman0c69cad2017-08-21 12:12:51 -07003662status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003663 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3664 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003665{
3666 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003667 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003668 case PIXEL_FORMAT_TRANSPARENT:
3669 case PIXEL_FORMAT_TRANSLUCENT:
3670 format = PIXEL_FORMAT_RGBA_8888;
3671 break;
3672 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003673 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003674 break;
3675 }
3676
David Sodman0c69cad2017-08-21 12:12:51 -07003677 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3678 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003679 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003680 *handle = layer->getHandle();
3681 *gbp = layer->getProducer();
3682 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003683 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003684
David Sodman0c69cad2017-08-21 12:12:51 -07003685 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003686 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003687}
3688
chaviw13fdc492017-06-27 12:40:18 -07003689status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003690 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003691 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003692{
chaviw13fdc492017-06-27 12:40:18 -07003693 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003694 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003695 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003696}
3697
Mathias Agopianac9fa422013-02-11 16:40:36 -08003698status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003699{
Robert Carr9524cb32017-02-13 11:32:32 -08003700 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003701 status_t err = NO_ERROR;
3702 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003703 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003704 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003705 err = removeLayer(l);
3706 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3707 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003708 }
3709 return err;
3710}
3711
Mathias Agopian13127d82013-03-05 17:47:11 -08003712status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003713{
Mathias Agopian67106042013-03-14 19:18:13 -07003714 // called by ~LayerCleaner() when all references to the IBinder (handle)
3715 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003716 sp<Layer> l = layer.promote();
3717 if (l == nullptr) {
3718 // The layer has already been removed, carry on
3719 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003720 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003721 // If we have a parent, then we can continue to live as long as it does.
3722 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003723}
3724
Mathias Agopianb60314a2012-04-10 22:09:54 -07003725// ---------------------------------------------------------------------------
3726
Andy McFadden13a082e2012-08-24 10:16:42 -07003727void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003728 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003729 Vector<ComposerState> state;
3730 Vector<DisplayState> displays;
3731 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003732 d.what = DisplayState::eDisplayProjectionChanged |
3733 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003734 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003735 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003736 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003737 d.frame.makeInvalid();
3738 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003739 d.width = 0;
3740 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003741 displays.add(d);
3742 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003743 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3744 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003745
David Sodman105b7dc2017-11-04 20:28:14 -07003746 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003747 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003748 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003749
Brian Andersond0010582017-03-07 13:20:31 -08003750 // Use phase of 0 since phase is not known.
3751 // Use latency of 0, which will snap to the ideal latency.
3752 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003753}
3754
3755void SurfaceFlinger::initializeDisplays() {
3756 class MessageScreenInitialized : public MessageBase {
3757 SurfaceFlinger* flinger;
3758 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003759 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003760 virtual bool handler() {
3761 flinger->onInitializeDisplays();
3762 return true;
3763 }
3764 };
3765 sp<MessageBase> msg = new MessageScreenInitialized(this);
3766 postMessageAsync(msg); // we may be called from main thread, use async message
3767}
3768
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003769void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003770 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003771 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3772 this);
3773 int32_t type = hw->getDisplayType();
3774 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003775
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003776 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003777 return;
3778 }
3779
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003780 hw->setPowerMode(mode);
3781 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3782 ALOGW("Trying to set power mode for virtual display");
3783 return;
3784 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003785
Lloyd Pique4dccc412018-01-22 17:21:36 -08003786 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003787 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003788 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3789 if (idx < 0) {
3790 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3791 return;
3792 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003793 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003794 }
3795
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003796 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003797 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003798 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003799 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3800 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003801 // FIXME: eventthread only knows about the main display right now
3802 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003803 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003804 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003805
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003806 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003807 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003808 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003809
3810 struct sched_param param = {0};
3811 param.sched_priority = 1;
3812 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3813 ALOGW("Couldn't set SCHED_FIFO on display on");
3814 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003815 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003816 // Turn off the display
3817 struct sched_param param = {0};
3818 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3819 ALOGW("Couldn't set SCHED_OTHER on display off");
3820 }
3821
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003822 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3823 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003824 disableHardwareVsync(true); // also cancels any in-progress resync
3825
Mathias Agopiancde87a32012-09-13 14:09:01 -07003826 // FIXME: eventthread only knows about the main display right now
3827 mEventThread->onScreenReleased();
3828 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003829
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003830 getHwComposer().setPowerMode(type, mode);
3831 mVisibleRegionsDirty = true;
3832 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003833 } else if (mode == HWC_POWER_MODE_DOZE ||
3834 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003835 // Update display while dozing
3836 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003837 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3838 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003839 // FIXME: eventthread only knows about the main display right now
3840 mEventThread->onScreenAcquired();
3841 resyncToHardwareVsync(true);
3842 }
3843 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3844 // Leave display going to doze
3845 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3846 disableHardwareVsync(true); // also cancels any in-progress resync
3847 // FIXME: eventthread only knows about the main display right now
3848 mEventThread->onScreenReleased();
3849 }
3850 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003851 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003852 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003853 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003854 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003855}
3856
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003857void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3858 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003859 SurfaceFlinger& mFlinger;
3860 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003861 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003862 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003863 MessageSetPowerMode(SurfaceFlinger& flinger,
3864 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3865 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003866 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003867 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003868 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003869 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003870 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003871 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003872 ALOGW("Attempt to set power mode = %d for virtual display",
3873 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003874 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003875 mFlinger.setPowerModeInternal(
3876 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003877 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003878 return true;
3879 }
3880 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003881 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003882 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003883}
3884
3885// ---------------------------------------------------------------------------
3886
Lloyd Pique755e3192018-01-31 16:46:15 -08003887status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3888 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003889 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003890
Mathias Agopianbd115332013-04-18 16:41:04 -07003891 IPCThreadState* ipc = IPCThreadState::self();
3892 const int pid = ipc->getCallingPid();
3893 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003894
Mathias Agopianbd115332013-04-18 16:41:04 -07003895 if ((uid != AID_SHELL) &&
3896 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003897 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003898 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003899 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003900 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003901 // (this would indicate SF is stuck, but we want to be able to
3902 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003903 status_t err = mStateLock.timedLock(s2ns(1));
3904 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003905 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003906 result.appendFormat(
3907 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3908 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003909 }
3910
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003911 bool dumpAll = true;
3912 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003913 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003914
3915 if (asProto) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003916 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviwa3d7bd32017-11-03 09:41:53 -07003917 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3918 dumpAll = false;
3919 }
3920
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003921 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003922 if ((index < numArgs) &&
3923 (args[index] == String16("--list"))) {
3924 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003925 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003926 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003927 }
3928
3929 if ((index < numArgs) &&
3930 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003931 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003932 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003933 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003934 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003935
3936 if ((index < numArgs) &&
3937 (args[index] == String16("--latency-clear"))) {
3938 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003939 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003940 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003941 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003942
3943 if ((index < numArgs) &&
3944 (args[index] == String16("--dispsync"))) {
3945 index++;
3946 mPrimaryDispSync.dump(result);
3947 dumpAll = false;
3948 }
Dan Stozab90cf072015-03-05 11:05:59 -08003949
3950 if ((index < numArgs) &&
3951 (args[index] == String16("--static-screen"))) {
3952 index++;
3953 dumpStaticScreenStats(result);
3954 dumpAll = false;
3955 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003956
3957 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003958 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003959 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003960 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003961 dumpAll = false;
3962 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003963
3964 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3965 index++;
3966 dumpWideColorInfo(result);
3967 dumpAll = false;
3968 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003969
3970 if ((index < numArgs) &&
3971 (args[index] == String16("--enable-layer-stats"))) {
3972 index++;
3973 mLayerStats.enable();
3974 dumpAll = false;
3975 }
3976
3977 if ((index < numArgs) &&
3978 (args[index] == String16("--disable-layer-stats"))) {
3979 index++;
3980 mLayerStats.disable();
3981 dumpAll = false;
3982 }
3983
3984 if ((index < numArgs) &&
3985 (args[index] == String16("--clear-layer-stats"))) {
3986 index++;
3987 mLayerStats.clear();
3988 dumpAll = false;
3989 }
3990
3991 if ((index < numArgs) &&
3992 (args[index] == String16("--dump-layer-stats"))) {
3993 index++;
3994 mLayerStats.dump(result);
3995 dumpAll = false;
3996 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003997 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003998
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003999 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004000 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004001 }
4002
Mathias Agopian9795c422009-08-26 16:36:26 -07004003 if (locked) {
4004 mStateLock.unlock();
4005 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004006 }
4007 write(fd, result.string(), result.size());
4008 return NO_ERROR;
4009}
4010
Dan Stozac7014012014-02-14 15:03:43 -08004011void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4012 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004013{
Robert Carr2047fae2016-11-28 14:09:09 -08004014 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004015 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004016 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004017}
4018
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004019void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004020 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004021{
4022 String8 name;
4023 if (index < args.size()) {
4024 name = String8(args[index]);
4025 index++;
4026 }
4027
David Sodman105b7dc2017-11-04 20:28:14 -07004028 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004029 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08004030 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004031
4032 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004033 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004034 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004035 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004036 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004037 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004038 }
Robert Carr2047fae2016-11-28 14:09:09 -08004039 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004040 }
4041}
4042
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004043void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004044 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004045{
4046 String8 name;
4047 if (index < args.size()) {
4048 name = String8(args[index]);
4049 index++;
4050 }
4051
Robert Carr2047fae2016-11-28 14:09:09 -08004052 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004053 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004054 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004055 }
Robert Carr2047fae2016-11-28 14:09:09 -08004056 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004057
Svetoslavd85084b2014-03-20 10:28:31 -07004058 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004059}
4060
Jamie Gennis6547ff42013-07-16 20:12:42 -07004061// This should only be called from the main thread. Otherwise it would need
4062// the lock and should use mCurrentState rather than mDrawingState.
4063void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004064 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004065 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004066 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004067
4068 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4069}
4070
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004071void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004072{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004073 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004074
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004075 if (isLayerTripleBufferingDisabled())
4076 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004077
4078 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004079 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004080 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004081 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004082 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4083 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004084 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004085}
4086
Dan Stozab90cf072015-03-05 11:05:59 -08004087void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4088{
4089 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004090 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4091 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004092 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004093 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004094 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4095 b + 1, bucketTimeSec, percent);
4096 }
David Sodman4a36e932017-11-07 14:29:47 -08004097 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004098 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004099 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004100 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004101 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004102}
4103
Dan Stozae77c7662016-05-13 11:37:28 -07004104void SurfaceFlinger::recordBufferingStats(const char* layerName,
4105 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004106 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4107 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004108 for (const auto& segment : history) {
4109 if (!segment.usedThirdBuffer) {
4110 stats.twoBufferTime += segment.totalTime;
4111 }
4112 if (segment.occupancyAverage < 1.0f) {
4113 stats.doubleBufferedTime += segment.totalTime;
4114 } else if (segment.occupancyAverage < 2.0f) {
4115 stats.tripleBufferedTime += segment.totalTime;
4116 }
4117 ++stats.numSegments;
4118 stats.totalTime += segment.totalTime;
4119 }
4120}
4121
Brian Andersond6927fb2016-07-23 23:37:30 -07004122void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4123 result.appendFormat("Layer frame timestamps:\n");
4124
4125 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4126 const size_t count = currentLayers.size();
4127 for (size_t i=0 ; i<count ; i++) {
4128 currentLayers[i]->dumpFrameEvents(result);
4129 }
4130}
4131
Dan Stozae77c7662016-05-13 11:37:28 -07004132void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4133 result.append("Buffering stats:\n");
4134 result.append(" [Layer name] <Active time> <Two buffer> "
4135 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004136 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004137 typedef std::tuple<std::string, float, float, float> BufferTuple;
4138 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004139 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004140 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004141 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004142 if (stats.numSegments == 0) {
4143 continue;
4144 }
4145 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4146 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4147 stats.totalTime;
4148 float doubleBufferRatio = static_cast<float>(
4149 stats.doubleBufferedTime) / stats.totalTime;
4150 float tripleBufferRatio = static_cast<float>(
4151 stats.tripleBufferedTime) / stats.totalTime;
4152 sorted.insert({activeTime, {name, twoBufferRatio,
4153 doubleBufferRatio, tripleBufferRatio}});
4154 }
4155 for (const auto& sortedPair : sorted) {
4156 float activeTime = sortedPair.first;
4157 const BufferTuple& values = sortedPair.second;
4158 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4159 std::get<0>(values).c_str(), activeTime,
4160 std::get<1>(values), std::get<2>(values),
4161 std::get<3>(values));
4162 }
4163 result.append("\n");
4164}
4165
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004166void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4167 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Romain Guy54f154a2017-10-24 21:40:32 +01004168 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004169
4170 // TODO: print out if wide-color mode is active or not
4171
4172 for (size_t d = 0; d < mDisplays.size(); d++) {
4173 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4174 int32_t hwcId = displayDevice->getHwcDisplayId();
4175 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4176 continue;
4177 }
4178
4179 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004180 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004181 for (auto&& mode : modes) {
4182 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4183 }
4184
Peiyong Lina52f0292018-03-14 17:26:31 -07004185 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004186 result.appendFormat(" Current color mode: %s (%d)\n",
4187 decodeColorMode(currentMode).c_str(), currentMode);
4188 }
4189 result.append("\n");
4190}
4191
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004192LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004193 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004194 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4195 const State& state = useDrawing ? mDrawingState : mCurrentState;
4196 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004197 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004198 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004199 });
4200
4201 return layersProto;
4202}
4203
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004204LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4205 LayersProto layersProto;
4206
4207 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
4208 SizeProto* resolution = layersProto.mutable_resolution();
4209 resolution->set_w(displayDevice->getWidth());
4210 resolution->set_h(displayDevice->getHeight());
4211
4212 mDrawingState.traverseInZOrder([&](Layer* layer) {
4213 if (!layer->visibleRegion.isEmpty() &&
4214 layer->getBE().mHwcLayers.count(hwcId)) {
4215 LayerProto* layerProto = layersProto.add_layers();
4216 layer->writeToProto(layerProto, hwcId);
4217 }
4218 });
4219
4220 return layersProto;
4221}
4222
Mathias Agopian74d211a2013-04-22 16:55:35 +02004223void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4224 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004225{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004226 bool colorize = false;
4227 if (index < args.size()
4228 && (args[index] == String16("--color"))) {
4229 colorize = true;
4230 index++;
4231 }
4232
4233 Colorizer colorizer(colorize);
4234
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004235 // figure out if we're stuck somewhere
4236 const nsecs_t now = systemTime();
4237 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4238 const nsecs_t inTransaction(mDebugInTransaction);
4239 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4240 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4241
4242 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004243 * Dump library configuration.
4244 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004245
4246 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004247 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004248 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004249 appendSfConfigString(result);
4250 appendUiConfigString(result);
4251 appendGuiConfigString(result);
4252 result.append("\n");
4253
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004254 result.append("\nWide-Color information:\n");
4255 dumpWideColorInfo(result);
4256
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004257 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004258 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004259 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004260 result.append(SyncFeatures::getInstance().toString());
4261 result.append("\n");
4262
David Sodman105b7dc2017-11-04 20:28:14 -07004263 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004264
Andy McFadden41d67d72014-04-25 16:58:34 -07004265 colorizer.bold(result);
4266 result.append("DispSync configuration: ");
4267 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07004268 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004269 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08004270 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004271 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004272 result.append("\n");
4273
Dan Stozab90cf072015-03-05 11:05:59 -08004274 // Dump static screen stats
4275 result.append("\n");
4276 dumpStaticScreenStats(result);
4277 result.append("\n");
4278
Dan Stozae77c7662016-05-13 11:37:28 -07004279 dumpBufferingStats(result);
4280
Andy McFadden4803b742012-09-24 19:07:20 -07004281 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004282 * Dump the visible layer list
4283 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004284 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004285 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004286 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4287 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004288 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004289
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004290 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004291 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004292 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004293
4294 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004295 * Dump Display state
4296 */
4297
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004298 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004299 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004300 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004301 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4302 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004303 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004304 }
4305
4306 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004307 * Dump SurfaceFlinger global state
4308 */
4309
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004310 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004311 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004312 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004313
Mathias Agopian888c8222012-08-04 21:10:38 -07004314 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004315 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004316
David Sodmanbc815282017-11-05 18:57:52 -08004317 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004318
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004319 if (hw) {
4320 hw->undefinedRegion.dump(result, "undefinedRegion");
4321 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4322 hw->getOrientation(), hw->isDisplayOn());
4323 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004324 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004325 " last eglSwapBuffers() time: %f us\n"
4326 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004327 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004328 " refresh-rate : %f fps\n"
4329 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004330 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004331 " gpu_to_cpu_unsupported : %d\n"
4332 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004333 mLastSwapBufferTime/1000.0,
4334 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004335 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004336 1e9 / activeConfig->getVsyncPeriod(),
4337 activeConfig->getDpiX(),
4338 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004339 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004340
Mathias Agopian74d211a2013-04-22 16:55:35 +02004341 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004342 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004343
Mathias Agopian74d211a2013-04-22 16:55:35 +02004344 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004345 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004346
4347 /*
4348 * VSYNC state
4349 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004350 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004351 result.append("\n");
4352
4353 /*
4354 * HWC layer minidump
4355 */
4356 for (size_t d = 0; d < mDisplays.size(); d++) {
4357 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4358 int32_t hwcId = displayDevice->getHwcDisplayId();
4359 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4360 continue;
4361 }
4362
4363 result.appendFormat("Display %d HWC layers:\n", hwcId);
4364 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004365 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004366 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004367 });
Dan Stozae22aec72016-08-01 13:20:59 -07004368 result.append("\n");
4369 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004370
4371 /*
4372 * Dump HWComposer state
4373 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004374 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004375 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004376 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004377 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004378 result.appendFormat(" h/w composer %s\n",
4379 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004380 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004381
4382 /*
4383 * Dump gralloc state
4384 */
4385 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4386 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004387
4388 /*
4389 * Dump VrFlinger state if in use.
4390 */
4391 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4392 result.append("VrFlinger state:\n");
4393 result.append(mVrFlinger->Dump().c_str());
4394 result.append("\n");
4395 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004396}
4397
Mathias Agopian13127d82013-03-05 17:47:11 -08004398const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004399SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004400 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004401 wp<IBinder> dpy;
4402 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4403 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4404 dpy = mDisplays.keyAt(i);
4405 break;
4406 }
4407 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004408 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004409 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4410 // Just use the primary display so we have something to return
4411 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4412 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004413 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004414}
4415
Keun young Park63f165f2012-08-31 10:53:36 -07004416bool SurfaceFlinger::startDdmConnection()
4417{
4418 void* libddmconnection_dso =
4419 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4420 if (!libddmconnection_dso) {
4421 return false;
4422 }
4423 void (*DdmConnection_start)(const char* name);
4424 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004425 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004426 if (!DdmConnection_start) {
4427 dlclose(libddmconnection_dso);
4428 return false;
4429 }
4430 (*DdmConnection_start)(getServiceName());
4431 return true;
4432}
4433
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004434status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004435 switch (code) {
4436 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004437 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004438 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004439 case CLEAR_ANIMATION_FRAME_STATS:
4440 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004441 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004442 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004443 case ENABLE_VSYNC_INJECTIONS:
4444 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004445 {
4446 // codes that require permission check
4447 IPCThreadState* ipc = IPCThreadState::self();
4448 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004449 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004450 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004451 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004452 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004453 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004454 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004455 break;
4456 }
Robert Carr1db73f62016-12-21 12:58:51 -08004457 /*
4458 * Calling setTransactionState is safe, because you need to have been
4459 * granted a reference to Client* and Handle* to do anything with it.
4460 *
4461 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4462 */
4463 case SET_TRANSACTION_STATE:
4464 case CREATE_SCOPED_CONNECTION:
4465 {
4466 return OK;
4467 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004468 case CAPTURE_SCREEN:
4469 {
4470 // codes that require permission check
4471 IPCThreadState* ipc = IPCThreadState::self();
4472 const int pid = ipc->getCallingPid();
4473 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004474 if ((uid != AID_GRAPHICS) &&
4475 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004476 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004477 return PERMISSION_DENIED;
4478 }
4479 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004480 }
chaviwa76b2712017-09-20 12:02:26 -07004481 case CAPTURE_LAYERS: {
4482 IPCThreadState* ipc = IPCThreadState::self();
4483 const int pid = ipc->getCallingPid();
4484 const int uid = ipc->getCallingUid();
4485 if ((uid != AID_GRAPHICS) &&
4486 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4487 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4488 return PERMISSION_DENIED;
4489 }
4490 break;
4491 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004492 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004493 return OK;
4494}
4495
4496status_t SurfaceFlinger::onTransact(
4497 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4498{
4499 status_t credentialCheck = CheckTransactCodeCredentials(code);
4500 if (credentialCheck != OK) {
4501 return credentialCheck;
4502 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004503
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004504 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4505 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004506 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004507 IPCThreadState* ipc = IPCThreadState::self();
4508 const int uid = ipc->getCallingUid();
4509 if (CC_UNLIKELY(uid != AID_SYSTEM
4510 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004511 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004512 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004513 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004514 return PERMISSION_DENIED;
4515 }
4516 int n;
4517 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004518 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004519 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004520 return NO_ERROR;
4521 case 1002: // SHOW_UPDATES
4522 n = data.readInt32();
4523 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004524 invalidateHwcGeometry();
4525 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004526 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004527 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004528 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004529 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004530 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004531 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004532 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004533 setTransactionFlags(
4534 eTransactionNeeded|
4535 eDisplayTransactionNeeded|
4536 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004537 return NO_ERROR;
4538 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004539 case 1006:{ // send empty update
4540 signalRefresh();
4541 return NO_ERROR;
4542 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004543 case 1008: // toggle use of hw composer
4544 n = data.readInt32();
4545 mDebugDisableHWC = n ? 1 : 0;
4546 invalidateHwcGeometry();
4547 repaintEverything();
4548 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004549 case 1009: // toggle use of transform hint
4550 n = data.readInt32();
4551 mDebugDisableTransformHint = n ? 1 : 0;
4552 invalidateHwcGeometry();
4553 repaintEverything();
4554 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004555 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004556 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004557 reply->writeInt32(0);
4558 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004559 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004560 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004561 return NO_ERROR;
4562 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004563 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004564 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004565 return NO_ERROR;
4566 }
4567 case 1014: {
4568 // daltonize
4569 n = data.readInt32();
4570 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004571 case 1:
4572 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4573 break;
4574 case 2:
4575 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4576 break;
4577 case 3:
4578 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4579 break;
4580 default:
4581 mDaltonizer.setType(ColorBlindnessType::None);
4582 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004583 }
4584 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004585 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004586 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004587 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004588 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004589 invalidateHwcGeometry();
4590 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004591 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004592 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004593 case 1015: {
4594 // apply a color matrix
4595 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004596 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004597 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004598 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004599 for (size_t j = 0; j < 4; j++) {
4600 mColorMatrix[i][j] = data.readFloat();
4601 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004602 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004603 } else {
4604 mColorMatrix = mat4();
4605 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004606
4607 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4608 // the division by w in the fragment shader
4609 float4 lastRow(transpose(mColorMatrix)[3]);
4610 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4611 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4612 }
4613
Alan Viverette9c5a3332013-09-12 20:04:35 -07004614 invalidateHwcGeometry();
4615 repaintEverything();
4616 return NO_ERROR;
4617 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004618 // This is an experimental interface
4619 // Needs to be shifted to proper binder interface when we productize
4620 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004621 n = data.readInt32();
4622 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004623 return NO_ERROR;
4624 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004625 case 1017: {
4626 n = data.readInt32();
4627 mForceFullDamage = static_cast<bool>(n);
4628 return NO_ERROR;
4629 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004630 case 1018: { // Modify Choreographer's phase offset
4631 n = data.readInt32();
4632 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4633 return NO_ERROR;
4634 }
4635 case 1019: { // Modify SurfaceFlinger's phase offset
4636 n = data.readInt32();
4637 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4638 return NO_ERROR;
4639 }
Irvel468051e2016-06-13 16:44:44 -07004640 case 1020: { // Layer updates interceptor
4641 n = data.readInt32();
4642 if (n) {
4643 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004644 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004645 }
4646 else{
4647 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004648 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004649 }
4650 return NO_ERROR;
4651 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004652 case 1021: { // Disable HWC virtual displays
4653 n = data.readInt32();
4654 mUseHwcVirtualDisplays = !n;
4655 return NO_ERROR;
4656 }
Romain Guy0147a172017-06-01 13:53:56 -07004657 case 1022: { // Set saturation boost
4658 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4659
4660 invalidateHwcGeometry();
4661 repaintEverything();
4662 return NO_ERROR;
4663 }
Romain Guy54f154a2017-10-24 21:40:32 +01004664 case 1023: { // Set native mode
4665 mForceNativeColorMode = data.readInt32() == 1;
4666
4667 invalidateHwcGeometry();
4668 repaintEverything();
4669 return NO_ERROR;
4670 }
4671 case 1024: { // Is wide color gamut rendering/color management supported?
4672 reply->writeBool(hasWideColorDisplay);
4673 return NO_ERROR;
4674 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004675 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004676 n = data.readInt32();
4677 if (n) {
4678 ALOGV("LayerTracing enabled");
4679 mTracing.enable();
4680 doTracing("tracing.enable");
4681 reply->writeInt32(NO_ERROR);
4682 } else {
4683 ALOGV("LayerTracing disabled");
4684 status_t err = mTracing.disable();
4685 reply->writeInt32(err);
4686 }
4687 return NO_ERROR;
4688 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004689 case 1026: { // Get layer tracing status
4690 reply->writeBool(mTracing.isEnabled());
4691 return NO_ERROR;
4692 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004693 }
4694 }
4695 return err;
4696}
4697
Steven Thomas6d8110b2017-08-31 18:24:21 -07004698void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004699 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004700 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004701}
4702
Steven Thomas6d8110b2017-08-31 18:24:21 -07004703void SurfaceFlinger::repaintEverything() {
4704 ConditionalLock _l(mStateLock,
4705 std::this_thread::get_id() != mMainThreadId);
4706 repaintEverythingLocked();
4707}
4708
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004709// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4710class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004711public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004712 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4713 ~WindowDisconnector() {
4714 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004715 }
4716
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004717private:
4718 ANativeWindow* mWindow;
4719 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004720};
4721
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004722status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4723 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4724 int32_t minLayerZ, int32_t maxLayerZ,
4725 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004726 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004727 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004728
chaviwa76b2712017-09-20 12:02:26 -07004729 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4730
4731 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004732 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4733
chaviwa76b2712017-09-20 12:02:26 -07004734 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4735
4736 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4737 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004738 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004739}
4740
4741status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004742 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004743 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004744 ATRACE_CALL();
4745
4746 class LayerRenderArea : public RenderArea {
4747 public:
Robert Carr578038f2018-03-09 12:25:24 -08004748 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4749 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
4750 : RenderArea(reqHeight, reqWidth),
4751 mLayer(layer),
4752 mCrop(crop),
4753 mFlinger(flinger),
4754 mChildrenOnly(childrenOnly) {}
chaviwa76b2712017-09-20 12:02:26 -07004755 Rect getBounds() const override {
4756 const Layer::State& layerState(mLayer->getDrawingState());
4757 return Rect(layerState.active.w, layerState.active.h);
4758 }
4759 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4760 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4761 bool isSecure() const override { return false; }
4762 bool needsFiltering() const override { return false; }
Robert Carr578038f2018-03-09 12:25:24 -08004763 const Transform& getTransform() const { return mTransform; }
4764
4765 class ReparentForDrawing {
4766 public:
4767 const sp<Layer>& oldParent;
4768 const sp<Layer>& newParent;
4769
4770 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4771 : oldParent(oldParent), newParent(newParent) {
4772 oldParent->reparentChildrenForDrawing(newParent);
4773 }
4774 ~ReparentForDrawing() { newParent->reparentChildrenForDrawing(oldParent); }
4775 };
4776
4777 void render(std::function<void()> drawLayers) override {
4778 if (!mChildrenOnly) {
4779 mTransform = mLayer->getTransform().inverse();
4780 drawLayers();
4781 } else {
4782 Rect bounds = getBounds();
4783 screenshotParentLayer =
4784 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4785 bounds.getWidth(), bounds.getHeight(), 0);
4786
4787 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4788 drawLayers();
4789 }
4790 }
chaviwa76b2712017-09-20 12:02:26 -07004791
chaviw7206d492017-11-10 16:16:12 -08004792 Rect getSourceCrop() const override {
4793 if (mCrop.isEmpty()) {
4794 return getBounds();
4795 } else {
4796 return mCrop;
4797 }
4798 }
chaviwa76b2712017-09-20 12:02:26 -07004799 bool getWideColorSupport() const override { return false; }
Peiyong Lina52f0292018-03-14 17:26:31 -07004800 ColorMode getActiveColorMode() const override { return ColorMode::NATIVE; }
chaviwa76b2712017-09-20 12:02:26 -07004801
4802 private:
chaviw7206d492017-11-10 16:16:12 -08004803 const sp<Layer> mLayer;
4804 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004805
4806 // In the "childrenOnly" case we reparent the children to a screenshot
4807 // layer which has no properties set and which does not draw.
4808 sp<ContainerLayer> screenshotParentLayer;
4809 Transform mTransform;
4810
4811 SurfaceFlinger* mFlinger;
4812 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004813 };
4814
4815 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4816 auto parent = layerHandle->owner.promote();
4817
chaviw7206d492017-11-10 16:16:12 -08004818 if (parent == nullptr || parent->isPendingRemoval()) {
4819 ALOGE("captureLayers called with a removed parent");
4820 return NAME_NOT_FOUND;
4821 }
4822
Robert Carr578038f2018-03-09 12:25:24 -08004823 const int uid = IPCThreadState::self()->getCallingUid();
4824 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4825 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4826 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4827 return PERMISSION_DENIED;
4828 }
4829
chaviw7206d492017-11-10 16:16:12 -08004830 Rect crop(sourceCrop);
4831 if (sourceCrop.width() <= 0) {
4832 crop.left = 0;
4833 crop.right = parent->getCurrentState().active.w;
4834 }
4835
4836 if (sourceCrop.height() <= 0) {
4837 crop.top = 0;
4838 crop.bottom = parent->getCurrentState().active.h;
4839 }
4840
4841 int32_t reqWidth = crop.width() * frameScale;
4842 int32_t reqHeight = crop.height() * frameScale;
4843
Robert Carr578038f2018-03-09 12:25:24 -08004844 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004845
Robert Carr578038f2018-03-09 12:25:24 -08004846 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004847 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4848 if (!layer->isVisible()) {
4849 return;
Robert Carr578038f2018-03-09 12:25:24 -08004850 } else if (childrenOnly && layer == parent.get()) {
4851 return;
chaviwa76b2712017-09-20 12:02:26 -07004852 }
4853 visitor(layer);
4854 });
4855 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004856 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004857}
4858
4859status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4860 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004861 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004862 bool useIdentityTransform) {
4863 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004864
chaviwa76b2712017-09-20 12:02:26 -07004865 renderArea.updateDimensions();
4866
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004867 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4868 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4869 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4870 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004871
4872 // This mutex protects syncFd and captureResult for communication of the return values from the
4873 // main thread back to this Binder thread
4874 std::mutex captureMutex;
4875 std::condition_variable captureCondition;
4876 std::unique_lock<std::mutex> captureLock(captureMutex);
4877 int syncFd = -1;
4878 std::optional<status_t> captureResult;
4879
Robert Carr03480e22018-01-04 16:02:06 -08004880 const int uid = IPCThreadState::self()->getCallingUid();
4881 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4882
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004883 sp<LambdaMessage> message = new LambdaMessage([&]() {
4884 // If there is a refresh pending, bug out early and tell the binder thread to try again
4885 // after the refresh.
4886 if (mRefreshPending) {
4887 ATRACE_NAME("Skipping screenshot for now");
4888 std::unique_lock<std::mutex> captureLock(captureMutex);
4889 captureResult = std::make_optional<status_t>(EAGAIN);
4890 captureCondition.notify_one();
4891 return;
4892 }
4893
4894 status_t result = NO_ERROR;
4895 int fd = -1;
4896 {
4897 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004898 renderArea.render([&]() {
4899 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4900 useIdentityTransform, forSystem, &fd);
4901 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004902 }
4903
4904 {
4905 std::unique_lock<std::mutex> captureLock(captureMutex);
4906 syncFd = fd;
4907 captureResult = std::make_optional<status_t>(result);
4908 captureCondition.notify_one();
4909 }
4910 });
4911
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004912 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004913 if (result == NO_ERROR) {
4914 captureCondition.wait(captureLock, [&]() { return captureResult; });
4915 while (*captureResult == EAGAIN) {
4916 captureResult.reset();
4917 result = postMessageAsync(message);
4918 if (result != NO_ERROR) {
4919 return result;
4920 }
4921 captureCondition.wait(captureLock, [&]() { return captureResult; });
4922 }
4923 result = *captureResult;
4924 }
4925
4926 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004927 sync_wait(syncFd, -1);
4928 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004929 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004930
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004931 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004932}
4933
chaviwa76b2712017-09-20 12:02:26 -07004934void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4935 TraverseLayersFunction traverseLayers, bool yswap,
4936 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004937 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004938
Lloyd Pique144e1162017-12-20 16:44:52 -08004939 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004940
4941 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004942 const auto raWidth = renderArea.getWidth();
4943 const auto raHeight = renderArea.getHeight();
4944
4945 const auto reqWidth = renderArea.getReqWidth();
4946 const auto reqHeight = renderArea.getReqHeight();
4947 Rect sourceCrop = renderArea.getSourceCrop();
4948
4949 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4950 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004951
Dan Stozac1879002014-05-22 15:59:05 -07004952 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004953 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004954 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004955 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004956 }
4957
4958 // ensure that sourceCrop is inside screen
4959 if (sourceCrop.left < 0) {
4960 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4961 }
chaviwa76b2712017-09-20 12:02:26 -07004962 if (sourceCrop.right > raWidth) {
4963 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004964 }
4965 if (sourceCrop.top < 0) {
4966 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4967 }
chaviwa76b2712017-09-20 12:02:26 -07004968 if (sourceCrop.bottom > raHeight) {
4969 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004970 }
4971
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004972 android_dataspace outputDataspace = HAL_DATASPACE_UNKNOWN;
Chia-I Wu9a48a8c2018-02-20 14:27:30 -08004973 if (renderArea.getWideColorSupport() &&
Peiyong Lina52f0292018-03-14 17:26:31 -07004974 renderArea.getActiveColorMode() == ColorMode::DISPLAY_P3) {
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004975 outputDataspace = HAL_DATASPACE_DISPLAY_P3;
4976 }
4977 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Romain Guy88d37dd2017-05-26 17:57:05 -07004978
Mathias Agopian180f10d2013-04-10 22:55:41 -07004979 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004980 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004981
4982 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004983 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4984 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004985 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004986
4987 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004988 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004989
chaviwa76b2712017-09-20 12:02:26 -07004990 traverseLayers([&](Layer* layer) {
4991 if (filtering) layer->setFiltering(true);
David Sodmandc5e0622018-01-05 23:10:57 -08004992 layer->drawNow(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004993 if (filtering) layer->setFiltering(false);
4994 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004995}
4996
chaviwa76b2712017-09-20 12:02:26 -07004997status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4998 TraverseLayersFunction traverseLayers,
4999 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005000 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005001 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005002 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005003 ATRACE_CALL();
5004
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005005 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005006
5007 traverseLayers([&](Layer* layer) {
5008 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5009 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005010
Robert Carr03480e22018-01-04 16:02:06 -08005011 // We allow the system server to take screenshots of secure layers for
5012 // use in situations like the Screen-rotation animation and place
5013 // the impetus on WindowManager to not persist them.
5014 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005015 ALOGW("FB is protected: PERMISSION_DENIED");
5016 return PERMISSION_DENIED;
5017 }
5018
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005019 // this binds the given EGLImage as a framebuffer for the
5020 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005021 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005022 if (bufferBond.getStatus() != NO_ERROR) {
5023 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005024 return INVALID_OPERATION;
5025 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005026
Dan Stozaabcda352017-06-01 14:37:39 -07005027 // this will in fact render into our dequeued buffer
5028 // via an FBO, which means we didn't have to create
5029 // an EGLSurface and therefore we're not
5030 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005031 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005032
Dan Stozaabcda352017-06-01 14:37:39 -07005033 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005034 getRenderEngine().finish();
5035 *outSyncFd = -1;
5036
chaviwa76b2712017-09-20 12:02:26 -07005037 const auto reqWidth = renderArea.getReqWidth();
5038 const auto reqHeight = renderArea.getReqHeight();
5039
Dan Stozaabcda352017-06-01 14:37:39 -07005040 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5041 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005042 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005043 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005044 } else {
5045 base::unique_fd syncFd = getRenderEngine().flush();
5046 if (syncFd < 0) {
5047 getRenderEngine().finish();
5048 }
5049 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005050 }
5051
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005052 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005053}
5054
Mathias Agopiand5556842013-09-19 17:08:37 -07005055void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005056 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005057 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005058 for (size_t y = 0; y < h; y++) {
5059 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5060 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005061 if (p[x] != 0xFF000000) return;
5062 }
5063 }
chaviwa76b2712017-09-20 12:02:26 -07005064 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005065
Robert Carr2047fae2016-11-28 14:09:09 -08005066 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005067 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005068 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005069 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5070 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5071 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5072 static_cast<float>(state.color.a));
5073 i++;
5074 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005075 }
5076}
5077
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005078// ---------------------------------------------------------------------------
5079
Dan Stoza412903f2017-04-27 13:42:17 -07005080void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5081 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005082}
5083
Dan Stoza412903f2017-04-27 13:42:17 -07005084void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5085 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005086}
5087
chaviwa76b2712017-09-20 12:02:26 -07005088void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
5089 int32_t maxLayerZ,
5090 const LayerVector::Visitor& visitor) {
5091 // We loop through the first level of layers without traversing,
5092 // as we need to interpret min/max layer Z in the top level Z space.
5093 for (const auto& layer : mDrawingState.layersSortedByZ) {
5094 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5095 continue;
5096 }
5097 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005098 // relative layers are traversed in Layer::traverseInZOrder
5099 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005100 continue;
5101 }
5102 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005103 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5104 return;
5105 }
chaviwa76b2712017-09-20 12:02:26 -07005106 if (!layer->isVisible()) {
5107 return;
5108 }
5109 visitor(layer);
5110 });
5111 }
5112}
5113
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005114}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005115
Mathias Agopian3f844832013-08-07 21:24:32 -07005116#if defined(__gl_h_)
5117#error "don't include gl/gl.h in this file"
5118#endif
5119
5120#if defined(__gl2_h_)
5121#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005122#endif