blob: b7931bc2af4d4ff1b274b866efab07e635c4beed [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();
677
David Sodmanbc815282017-11-05 18:57:52 -0800678 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700679
Wei Wangf9b05ee2017-07-19 20:59:39 -0700680 // Inform native graphics APIs whether the present timestamp is supported:
681 if (getHwComposer().hasCapability(
682 HWC2::Capability::PresentFenceIsNotReliable)) {
683 mStartPropertySetThread = new StartPropertySetThread(false);
684 } else {
685 mStartPropertySetThread = new StartPropertySetThread(true);
686 }
687
688 if (mStartPropertySetThread->Start() != NO_ERROR) {
689 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800690 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800691
Dan Stoza9e56aa02015-11-02 13:00:03 -0800692 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700693}
694
Romain Guy11d63f42017-07-20 12:47:14 -0700695void SurfaceFlinger::readPersistentProperties() {
696 char value[PROPERTY_VALUE_MAX];
697
698 property_get("persist.sys.sf.color_saturation", value, "1.0");
699 mSaturation = atof(value);
700 ALOGV("Saturation is set to %.2f", mSaturation);
Romain Guy54f154a2017-10-24 21:40:32 +0100701
702 property_get("persist.sys.sf.native_mode", value, "0");
703 mForceNativeColorMode = atoi(value) == 1;
704 if (mForceNativeColorMode) {
705 ALOGV("Forcing native color mode");
706 }
Romain Guy11d63f42017-07-20 12:47:14 -0700707}
708
Mathias Agopiana67e4182012-06-19 17:26:12 -0700709void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800710 // Start boot animation service by setting a property mailbox
711 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700712 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800713 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700714 if (mStartPropertySetThread->join() != NO_ERROR) {
715 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800716 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700717}
718
Mathias Agopian875d8e12013-06-07 15:35:48 -0700719size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800720 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700721}
722
Mathias Agopian875d8e12013-06-07 15:35:48 -0700723size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800724 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700725}
726
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800727// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800728
Jamie Gennis582270d2011-08-17 18:19:00 -0700729bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800730 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800731 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800732 return authenticateSurfaceTextureLocked(bufferProducer);
733}
734
735bool SurfaceFlinger::authenticateSurfaceTextureLocked(
736 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800737 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800738 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800739}
740
Brian Anderson6b376712017-04-04 10:51:39 -0700741status_t SurfaceFlinger::getSupportedFrameTimestamps(
742 std::vector<FrameEvent>* outSupported) const {
743 *outSupported = {
744 FrameEvent::REQUESTED_PRESENT,
745 FrameEvent::ACQUIRE,
746 FrameEvent::LATCH,
747 FrameEvent::FIRST_REFRESH_START,
748 FrameEvent::LAST_REFRESH_START,
749 FrameEvent::GPU_COMPOSITION_DONE,
750 FrameEvent::DEQUEUE_READY,
751 FrameEvent::RELEASE,
752 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700753 ConditionalLock _l(mStateLock,
754 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700755 if (!getHwComposer().hasCapability(
756 HWC2::Capability::PresentFenceIsNotReliable)) {
757 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
758 }
759 return NO_ERROR;
760}
761
Dan Stoza7f7da322014-05-02 15:26:25 -0700762status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
763 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800764 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700765 return BAD_VALUE;
766 }
767
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500768 if (!display.get())
769 return NAME_NOT_FOUND;
770
Jesse Hall692c7232012-11-08 15:41:56 -0800771 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700772 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800773 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700774 type = i;
775 break;
776 }
777 }
778
779 if (type < 0) {
780 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700781 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700782
Mathias Agopian8b736f12012-08-13 17:54:26 -0700783 // TODO: Not sure if display density should handled by SF any longer
784 class Density {
785 static int getDensityFromProperty(char const* propName) {
786 char property[PROPERTY_VALUE_MAX];
787 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800788 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700789 density = atoi(property);
790 }
791 return density;
792 }
793 public:
794 static int getEmuDensity() {
795 return getDensityFromProperty("qemu.sf.lcd_density"); }
796 static int getBuildDensity() {
797 return getDensityFromProperty("ro.sf.lcd_density"); }
798 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700799
Dan Stoza7f7da322014-05-02 15:26:25 -0700800 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700801
Steven Thomas6d8110b2017-08-31 18:24:21 -0700802 ConditionalLock _l(mStateLock,
803 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800804 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700805 DisplayInfo info = DisplayInfo();
806
Dan Stoza9e56aa02015-11-02 13:00:03 -0800807 float xdpi = hwConfig->getDpiX();
808 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700809
810 if (type == DisplayDevice::DISPLAY_PRIMARY) {
811 // The density of the device is provided by a build property
812 float density = Density::getBuildDensity() / 160.0f;
813 if (density == 0) {
814 // the build doesn't provide a density -- this is wrong!
815 // use xdpi instead
816 ALOGE("ro.sf.lcd_density must be defined as a build property");
817 density = xdpi / 160.0f;
818 }
819 if (Density::getEmuDensity()) {
820 // if "qemu.sf.lcd_density" is specified, it overrides everything
821 xdpi = ydpi = density = Density::getEmuDensity();
822 density /= 160.0f;
823 }
824 info.density = density;
825
826 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700827 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800828 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700829 } else {
830 // TODO: where should this value come from?
831 static const int TV_DENSITY = 213;
832 info.density = TV_DENSITY / 160.0f;
833 info.orientation = 0;
834 }
835
Dan Stoza9e56aa02015-11-02 13:00:03 -0800836 info.w = hwConfig->getWidth();
837 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700838 info.xdpi = xdpi;
839 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800840 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900841 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800842
Andy McFadden91b2ca82014-06-13 14:04:23 -0700843 // This is how far in advance a buffer must be queued for
844 // presentation at a given time. If you want a buffer to appear
845 // on the screen at time N, you must submit the buffer before
846 // (N - presentationDeadline).
847 //
848 // Normally it's one full refresh period (to give SF a chance to
849 // latch the buffer), but this can be reduced by configuring a
850 // DispSync offset. Any additional delays introduced by the hardware
851 // composer or panel must be accounted for here.
852 //
853 // We add an additional 1ms to allow for processing time and
854 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800855 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800856 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700857
858 // All non-virtual displays are currently considered secure.
859 info.secure = true;
860
Michael Wright28f24d02016-07-12 13:30:53 -0700861 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700862 }
863
Dan Stoza7f7da322014-05-02 15:26:25 -0700864 return NO_ERROR;
865}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700866
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800867status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700868 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800869 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700870 return BAD_VALUE;
871 }
872
873 // FIXME for now we always return stats for the primary display
874 memset(stats, 0, sizeof(*stats));
875 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
876 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
877 return NO_ERROR;
878}
879
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700880int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800881 if (display == nullptr) {
882 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800883 return BAD_VALUE;
884 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700885
886 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800887 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700888 return device->getActiveConfig();
889 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700890
Dan Stoza24a42e92015-03-09 10:04:11 -0700891 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700892}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700893
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700894void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
895 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
896 this);
897 int32_t type = hw->getDisplayType();
898 int currentMode = hw->getActiveConfig();
899
900 if (mode == currentMode) {
901 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
902 return;
903 }
904
905 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
906 ALOGW("Trying to set config for virtual display");
907 return;
908 }
909
910 hw->setActiveConfig(mode);
911 getHwComposer().setActiveConfig(type, mode);
912}
913
914status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
915 class MessageSetActiveConfig: public MessageBase {
916 SurfaceFlinger& mFlinger;
917 sp<IBinder> mDisplay;
918 int mMode;
919 public:
920 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
921 int mode) :
922 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
923 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700924 Vector<DisplayInfo> configs;
925 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700926 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700927 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700928 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700929 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700930 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700931 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800932 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700933 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700934 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700935 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
936 ALOGW("Attempt to set active config = %d for virtual display",
937 mMode);
938 } else {
939 mFlinger.setActiveConfigInternal(hw, mMode);
940 }
941 return true;
942 }
943 };
944 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
945 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700946 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700947}
Michael Wright28f24d02016-07-12 13:30:53 -0700948status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -0700949 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700950 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
951 return BAD_VALUE;
952 }
953
954 if (!display.get()) {
955 return NAME_NOT_FOUND;
956 }
957
958 int32_t type = NAME_NOT_FOUND;
959 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
960 if (display == mBuiltinDisplays[i]) {
961 type = i;
962 break;
963 }
964 }
965
966 if (type < 0) {
967 return type;
968 }
969
Peiyong Lina52f0292018-03-14 17:26:31 -0700970 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700971 {
972 ConditionalLock _l(mStateLock,
973 std::this_thread::get_id() != mMainThreadId);
974 modes = getHwComposer().getColorModes(type);
975 }
Michael Wright28f24d02016-07-12 13:30:53 -0700976 outColorModes->clear();
977 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
978
979 return NO_ERROR;
980}
981
Peiyong Lina52f0292018-03-14 17:26:31 -0700982ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700983 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700984 if (device != nullptr) {
985 return device->getActiveColorMode();
986 }
Peiyong Lina52f0292018-03-14 17:26:31 -0700987 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -0700988}
989
990void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lina52f0292018-03-14 17:26:31 -0700991 ColorMode mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700992 int32_t type = hw->getDisplayType();
Peiyong Lina52f0292018-03-14 17:26:31 -0700993 ColorMode currentMode = hw->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -0700994
995 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700996 return;
997 }
998
999 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1000 ALOGW("Trying to set config for virtual display");
1001 return;
1002 }
1003
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001004 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
1005 hw->getDisplayType());
1006
Michael Wright28f24d02016-07-12 13:30:53 -07001007 hw->setActiveColorMode(mode);
1008 getHwComposer().setActiveColorMode(type, mode);
1009}
1010
1011
1012status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001013 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -07001014 class MessageSetActiveColorMode: public MessageBase {
1015 SurfaceFlinger& mFlinger;
1016 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -07001017 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001018 public:
1019 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -07001020 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -07001021 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1022 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -07001023 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001024 mFlinger.getDisplayColorModes(mDisplay, &modes);
1025 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -07001026 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001027 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1028 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001029 return true;
1030 }
1031 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1032 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001033 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1034 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001035 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001036 ALOGW("Attempt to set active color mode %s %d for virtual display",
1037 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001038 } else {
1039 mFlinger.setActiveColorModeInternal(hw, mMode);
1040 }
1041 return true;
1042 }
1043 };
1044 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1045 postMessageSync(msg);
1046 return NO_ERROR;
1047}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001048
Svetoslavd85084b2014-03-20 10:28:31 -07001049status_t SurfaceFlinger::clearAnimationFrameStats() {
1050 Mutex::Autolock _l(mStateLock);
1051 mAnimFrameTracker.clearStats();
1052 return NO_ERROR;
1053}
1054
1055status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1056 Mutex::Autolock _l(mStateLock);
1057 mAnimFrameTracker.getStats(outStats);
1058 return NO_ERROR;
1059}
1060
Dan Stozac4f471e2016-03-24 09:31:08 -07001061status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1062 HdrCapabilities* outCapabilities) const {
1063 Mutex::Autolock _l(mStateLock);
1064
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001065 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001066 if (displayDevice == nullptr) {
1067 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1068 return BAD_VALUE;
1069 }
1070
1071 std::unique_ptr<HdrCapabilities> capabilities =
David Sodman105b7dc2017-11-04 20:28:14 -07001072 getBE().mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
Dan Stozac4f471e2016-03-24 09:31:08 -07001073 if (capabilities) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001074 if (displayDevice->getWideColorSupport() && !displayDevice->getHdrSupport()) {
1075 // insert HDR10 as we will force client composition for HDR10
1076 // layers
1077 std::vector<int32_t> types = capabilities->getSupportedHdrTypes();
1078 types.push_back(HAL_HDR_HDR10);
1079
1080 *outCapabilities = HdrCapabilities(types,
1081 capabilities->getDesiredMaxLuminance(),
1082 capabilities->getDesiredMaxAverageLuminance(),
1083 capabilities->getDesiredMinLuminance());
1084 } else {
1085 *outCapabilities = std::move(*capabilities);
1086 }
Dan Stozac4f471e2016-03-24 09:31:08 -07001087 } else {
1088 return BAD_VALUE;
1089 }
1090
1091 return NO_ERROR;
1092}
1093
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001094status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001095 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1096 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001097
Chia-I Wu90f669f2017-10-05 14:24:41 -07001098 if (mInjectVSyncs == enable) {
1099 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001100 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001101
1102 if (enable) {
1103 ALOGV("VSync Injections enabled");
1104 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001105 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique0fcde1b2017-12-20 16:50:21 -08001106 mInjectorEventThread =
1107 std::make_unique<impl::EventThread>(mVSyncInjector.get(), *this, false,
1108 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001109 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001110 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001111 } else {
1112 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001113 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001114 }
1115
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001116 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001117 });
1118 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001119 return NO_ERROR;
1120}
1121
1122status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001123 Mutex::Autolock _l(mStateLock);
1124
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001125 if (!mInjectVSyncs) {
1126 ALOGE("VSync Injections not enabled");
1127 return BAD_VALUE;
1128 }
1129 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1130 ALOGV("Injecting VSync inside SurfaceFlinger");
1131 mVSyncInjector->onInjectSyncEvent(when);
1132 }
1133 return NO_ERROR;
1134}
1135
Lloyd Pique755e3192018-01-31 16:46:15 -08001136status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1137 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001138 IPCThreadState* ipc = IPCThreadState::self();
1139 const int pid = ipc->getCallingPid();
1140 const int uid = ipc->getCallingUid();
1141 if ((uid != AID_SHELL) &&
1142 !PermissionCache::checkPermission(sDump, pid, uid)) {
1143 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1144 return PERMISSION_DENIED;
1145 }
1146
1147 // Try to acquire a lock for 1s, fail gracefully
1148 const status_t err = mStateLock.timedLock(s2ns(1));
1149 const bool locked = (err == NO_ERROR);
1150 if (!locked) {
1151 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1152 return TIMED_OUT;
1153 }
1154
1155 outLayers->clear();
1156 mCurrentState.traverseInZOrder([&](Layer* layer) {
1157 outLayers->push_back(layer->getLayerDebugInfo());
1158 });
1159
1160 mStateLock.unlock();
1161 return NO_ERROR;
1162}
1163
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001164// ----------------------------------------------------------------------------
1165
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001166sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1167 ISurfaceComposer::VsyncSource vsyncSource) {
1168 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1169 return mSFEventThread->createEventConnection();
1170 } else {
1171 return mEventThread->createEventConnection();
1172 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001173}
1174
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001175// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001176
1177void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001178 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001179}
1180
1181void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001182 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001183}
1184
1185void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001186 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001187}
1188
1189void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001190 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001191 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001192}
1193
1194status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001195 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001196 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001197}
1198
1199status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001200 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001201 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001202 if (res == NO_ERROR) {
1203 msg->wait();
1204 }
1205 return res;
1206}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001207
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001208void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001209 do {
1210 waitForEvent();
1211 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001212}
1213
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001214void SurfaceFlinger::enableHardwareVsync() {
1215 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001216 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001217 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001218 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1219 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001220 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001221 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001222}
1223
Jesse Hall948fe0c2013-10-14 12:56:09 -07001224void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001225 Mutex::Autolock _l(mHWVsyncLock);
1226
Jesse Hall948fe0c2013-10-14 12:56:09 -07001227 if (makeAvailable) {
1228 mHWVsyncAvailable = true;
1229 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001230 // Hardware vsync is not currently available, so abort the resync
1231 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001232 return;
1233 }
1234
David Sodman105b7dc2017-11-04 20:28:14 -07001235 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001236 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001237
1238 mPrimaryDispSync.reset();
1239 mPrimaryDispSync.setPeriod(period);
1240
1241 if (!mPrimaryHWVsyncEnabled) {
1242 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001243 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1244 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001245 mPrimaryHWVsyncEnabled = true;
1246 }
1247}
1248
Jesse Hall948fe0c2013-10-14 12:56:09 -07001249void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001250 Mutex::Autolock _l(mHWVsyncLock);
1251 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001252 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1253 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001254 mPrimaryDispSync.endResync();
1255 mPrimaryHWVsyncEnabled = false;
1256 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001257 if (makeUnavailable) {
1258 mHWVsyncAvailable = false;
1259 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001260}
1261
Tim Murray4a4e4a22016-04-19 16:29:23 +00001262void SurfaceFlinger::resyncWithRateLimit() {
1263 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001264
1265 // No explicit locking is needed here since EventThread holds a lock while calling this method
1266 static nsecs_t sLastResyncAttempted = 0;
1267 const nsecs_t now = systemTime();
1268 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001269 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001270 }
Dan Stoza57164302017-05-08 14:03:54 -07001271 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001272}
1273
Steven Thomasb02664d2017-07-26 18:48:28 -07001274void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1275 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001276 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001277 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001278 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001279 return;
1280 }
1281
1282 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001283 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001284 return;
1285 }
1286
Jamie Gennisd1700752013-10-14 12:22:52 -07001287 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001288
Jamie Gennisd1700752013-10-14 12:22:52 -07001289 { // Scope for the lock
1290 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001291 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001292 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001293 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001294 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001295
1296 if (needsHwVsync) {
1297 enableHardwareVsync();
1298 } else {
1299 disableHardwareVsync(false);
1300 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001301}
1302
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001303void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001304 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1305 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001306}
1307
Lloyd Pique715a2c12017-12-14 17:18:08 -08001308void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1309 HWC2::Connection connection) {
1310 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1311 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001312
Lloyd Piqueba04e622017-12-14 17:11:26 -08001313 // Ignore events that do not have the right sequenceId.
1314 if (sequenceId != getBE().mComposerSequenceId) {
1315 return;
1316 }
1317
Steven Thomasb02664d2017-07-26 18:48:28 -07001318 // Only lock if we're not on the main thread. This function is normally
1319 // called on a hwbinder thread, but for the primary display it's called on
1320 // the main thread with the state lock already held, so don't attempt to
1321 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001322 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001323
Lloyd Pique715a2c12017-12-14 17:18:08 -08001324 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001325
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001326 if (std::this_thread::get_id() == mMainThreadId) {
1327 // Process all pending hot plug events immediately if we are on the main thread.
1328 processDisplayHotplugEventsLocked();
1329 }
1330
Lloyd Piqueba04e622017-12-14 17:11:26 -08001331 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001332}
1333
Steven Thomasb02664d2017-07-26 18:48:28 -07001334void SurfaceFlinger::onRefreshReceived(int sequenceId,
1335 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001336 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001337 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001338 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001339 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001340 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001341}
1342
Dan Stoza9e56aa02015-11-02 13:00:03 -08001343void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001344 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001345 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001346 getHwComposer().setVsyncEnabled(disp,
1347 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001348}
1349
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001350// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001351void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001352 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001353 // Clear the drawing state so that the logic inside of
1354 // handleTransactionLocked will fire. It will determine the delta between
1355 // mCurrentState and mDrawingState and re-apply all changes when we make the
1356 // transition.
1357 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001358 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001359 mDisplays.clear();
1360}
1361
Steven Thomas050b2c82017-03-06 11:45:16 -08001362void SurfaceFlinger::updateVrFlinger() {
1363 if (!mVrFlinger)
1364 return;
1365 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001366 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001367 return;
1368 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001369
David Sodman105b7dc2017-11-04 20:28:14 -07001370 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001371 ALOGE("Vr flinger is only supported for remote hardware composer"
1372 " service connections. Ignoring request to transition to vr"
1373 " flinger.");
1374 mVrFlingerRequestsDisplay = false;
1375 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001376 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001377
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001378 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001379
Steven Thomasb02664d2017-07-26 18:48:28 -07001380 int currentDisplayPowerMode = getDisplayDeviceLocked(
1381 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001382
Steven Thomasb02664d2017-07-26 18:48:28 -07001383 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001384 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001385 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001386
Steven Thomasb02664d2017-07-26 18:48:28 -07001387 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001388 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001389 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1390 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001391 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001392
David Sodman105b7dc2017-11-04 20:28:14 -07001393 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1394 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001395
1396 if (vrFlingerRequestsDisplay) {
1397 mVrFlinger->GrantDisplayOwnership();
1398 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001399 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001400 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001401
1402 mVisibleRegionsDirty = true;
1403 invalidateHwcGeometry();
1404
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001405 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001406 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1407 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1408 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001409
Steven Thomasb02664d2017-07-26 18:48:28 -07001410 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001411 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001412 const nsecs_t period = activeConfig->getVsyncPeriod();
1413 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001414
Steven Thomasb02664d2017-07-26 18:48:28 -07001415 // Use phase of 0 since phase is not known.
1416 // Use latency of 0, which will snap to the ideal latency.
1417 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001418
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001419 android_atomic_or(1, &mRepaintEverything);
1420 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001421}
1422
Mathias Agopian4fec8732012-06-29 14:12:52 -07001423void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001424 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001425 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001426 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001427 bool frameMissed = !mHadClientComposition &&
1428 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001429 (mPreviousPresentFence->getSignalTime() ==
1430 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001431 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001432 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001433 signalLayerUpdate();
1434 break;
1435 }
1436
Steven Thomas050b2c82017-03-06 11:45:16 -08001437 // Now that we're going to make it to the handleMessageTransaction()
1438 // call below it's safe to call updateVrFlinger(), which will
1439 // potentially trigger a display handoff.
1440 updateVrFlinger();
1441
Dan Stoza6b9454d2014-11-07 16:00:59 -08001442 bool refreshNeeded = handleMessageTransaction();
1443 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001444 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001445 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001446 // Signal a refresh if a transaction modified the window state,
1447 // a new buffer was latched, or if HWC has requested a full
1448 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001449 signalRefresh();
1450 }
1451 break;
1452 }
1453 case MessageQueue::REFRESH: {
1454 handleMessageRefresh();
1455 break;
1456 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001457 }
1458}
1459
Dan Stoza6b9454d2014-11-07 16:00:59 -08001460bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001461 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001462 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001463 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001464 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001465 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001466 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001467}
1468
Dan Stoza6b9454d2014-11-07 16:00:59 -08001469bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001470 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001471 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001472}
1473
1474void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001475 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001476
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001477 mRefreshPending = false;
1478
Chia-I Wu30505fb2018-03-26 16:20:31 -07001479 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001480
Chia-I Wu30505fb2018-03-26 16:20:31 -07001481 preComposition(refreshStartTime);
1482 rebuildLayerStacks();
1483 setUpHWComposer();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001484 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001485 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001486 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001487 doComposition();
Chia-I Wu30505fb2018-03-26 16:20:31 -07001488 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001489
David Sodman105b7dc2017-11-04 20:28:14 -07001490 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001491
1492 mHadClientComposition = false;
1493 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1494 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1495 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001496 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001497 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001498
Dan Stoza9e56aa02015-11-02 13:00:03 -08001499 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001500}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001501
Mathias Agopiancd60f992012-08-16 16:28:27 -07001502void SurfaceFlinger::doDebugFlashRegions()
1503{
1504 // is debugging enabled
1505 if (CC_LIKELY(!mDebugRegion))
1506 return;
1507
1508 const bool repaintEverything = mRepaintEverything;
1509 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1510 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001511 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001512 // transform the dirty region into this screen's coordinate space
1513 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1514 if (!dirtyRegion.isEmpty()) {
1515 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001516 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001517
1518 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001519 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001520 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001521 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1522
Mathias Agopianda27af92012-09-13 18:17:13 -07001523 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001524 }
1525 }
1526 }
1527
1528 postFramebuffer();
1529
1530 if (mDebugRegion > 1) {
1531 usleep(mDebugRegion * 1000);
1532 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001533
Dan Stoza9e56aa02015-11-02 13:00:03 -08001534 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001535 auto& displayDevice = mDisplays[displayId];
1536 if (!displayDevice->isDisplayOn()) {
1537 continue;
1538 }
1539
David Sodman105b7dc2017-11-04 20:28:14 -07001540 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1541 ALOGE_IF(result != NO_ERROR,
1542 "prepareFrame for display %zd failed:"
1543 " %d (%s)",
1544 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001545 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001546}
1547
Adrian Roos1e1a1282017-11-01 19:05:31 +01001548void SurfaceFlinger::doTracing(const char* where) {
1549 ATRACE_CALL();
1550 ATRACE_NAME(where);
1551 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001552 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001553 }
1554}
1555
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001556void SurfaceFlinger::logLayerStats() {
1557 ATRACE_CALL();
1558 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1559 int32_t hwcId = -1;
1560 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1561 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1562 if (displayDevice->isPrimary()) {
1563 hwcId = displayDevice->getHwcDisplayId();
1564 break;
1565 }
1566 }
1567 if (hwcId < 0) {
1568 ALOGE("LayerStats: Hmmm, no primary display?");
1569 return;
1570 }
1571 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1572 }
1573}
1574
Chia-I Wu30505fb2018-03-26 16:20:31 -07001575void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001576{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001577 ATRACE_CALL();
1578 ALOGV("preComposition");
1579
Mathias Agopiancd60f992012-08-16 16:28:27 -07001580 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001581 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001582 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001583 needExtraInvalidate = true;
1584 }
Robert Carr2047fae2016-11-28 14:09:09 -08001585 });
1586
Mathias Agopiancd60f992012-08-16 16:28:27 -07001587 if (needExtraInvalidate) {
1588 signalLayerUpdate();
1589 }
1590}
1591
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001592void SurfaceFlinger::updateCompositorTiming(
1593 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1594 std::shared_ptr<FenceTime>& presentFenceTime) {
1595 // Update queue of past composite+present times and determine the
1596 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001597 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001598 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001599 while (!getBE().mCompositePresentTimes.empty()) {
1600 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001601 // Cached values should have been updated before calling this method,
1602 // which helps avoid duplicate syscalls.
1603 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1604 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1605 break;
1606 }
1607 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001608 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001609 }
1610
1611 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001612 while (getBE().mCompositePresentTimes.size() > 16) {
1613 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001614 }
1615
Brian Andersond0010582017-03-07 13:20:31 -08001616 setCompositorTimingSnapped(
1617 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1618}
1619
1620void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1621 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001622 // Integer division and modulo round toward 0 not -inf, so we need to
1623 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001624 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001625 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1626 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1627
Brian Andersond0010582017-03-07 13:20:31 -08001628 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1629 if (idealLatency <= 0) {
1630 idealLatency = vsyncInterval;
1631 }
1632
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001633 // Snap the latency to a value that removes scheduling jitter from the
1634 // composition and present times, which often have >1ms of jitter.
1635 // Reducing jitter is important if an app attempts to extrapolate
1636 // something (such as user input) to an accurate diasplay time.
1637 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1638 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001639 nsecs_t bias = vsyncInterval / 2;
1640 int64_t extraVsyncs =
1641 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1642 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1643 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001644
David Sodman99974d22017-11-28 12:04:33 -08001645 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1646 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1647 getBE().mCompositorTiming.interval = vsyncInterval;
1648 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001649}
1650
Chia-I Wu30505fb2018-03-26 16:20:31 -07001651void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001652{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001653 ATRACE_CALL();
1654 ALOGV("postComposition");
1655
Brian Anderson3546a3f2016-07-14 11:51:14 -07001656 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001657 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001658 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001659 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001660 }
1661
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001662 // |mStateLock| not needed as we are on the main thread
1663 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001664
David Sodman73beded2017-11-15 11:56:06 -08001665 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001666 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001667 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001668 glCompositionDoneFenceTime =
1669 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001670 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001671 } else {
1672 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1673 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001674
David Sodman73beded2017-11-15 11:56:06 -08001675 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001676 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001677 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001678 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001679
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001680 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1681 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1682
Chia-I Wu30505fb2018-03-26 16:20:31 -07001683 // We use the refreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001684 // when we started doing work for this frame, but that should be okay
1685 // since updateCompositorTiming has snapping logic.
1686 updateCompositorTiming(
Chia-I Wu30505fb2018-03-26 16:20:31 -07001687 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001688 CompositorTiming compositorTiming;
1689 {
David Sodman99974d22017-11-28 12:04:33 -08001690 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1691 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001692 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001693
Robert Carr2047fae2016-11-28 14:09:09 -08001694 mDrawingState.traverseInZOrder([&](Layer* layer) {
1695 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001696 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001697 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001698 recordBufferingStats(layer->getName().string(),
1699 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001700 }
Robert Carr2047fae2016-11-28 14:09:09 -08001701 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001702
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001703 if (presentFenceTime->isValid()) {
1704 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001705 enableHardwareVsync();
1706 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001707 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001708 }
1709 }
1710
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001711 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001712 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001713 enableHardwareVsync();
1714 }
1715 }
1716
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001717 if (mAnimCompositionPending) {
1718 mAnimCompositionPending = false;
1719
Brian Anderson4e606e32017-03-16 15:34:57 -07001720 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001721 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001722 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001723 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001724 // The HWC doesn't support present fences, so use the refresh
1725 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001726 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001727 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001728 mAnimFrameTracker.setActualPresentTime(presentTime);
1729 }
1730 mAnimFrameTracker.advanceFrame();
1731 }
Dan Stozab90cf072015-03-05 11:05:59 -08001732
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001733 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1734 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001735 return;
1736 }
1737
1738 nsecs_t currentTime = systemTime();
1739 if (mHasPoweredOff) {
1740 mHasPoweredOff = false;
1741 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001742 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001743 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001744 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1745 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001746 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001747 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001748 }
David Sodman4a36e932017-11-07 14:29:47 -08001749 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001750 }
David Sodman4a36e932017-11-07 14:29:47 -08001751 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001752}
1753
1754void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001755 ATRACE_CALL();
1756 ALOGV("rebuildLayerStacks");
1757
Mathias Agopiancd60f992012-08-16 16:28:27 -07001758 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001759 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001760 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001761 mVisibleRegionsDirty = false;
1762 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001763
Jeff Sharkey76488112017-02-27 14:15:18 -07001764 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1765 Region opaqueRegion;
1766 Region dirtyRegion;
1767 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001768 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001769 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1770 const Transform& tr(displayDevice->getTransform());
1771 const Rect bounds(displayDevice->getBounds());
1772 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001773 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001774
Jeff Sharkey76488112017-02-27 14:15:18 -07001775 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001776 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001777 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1778 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001779 Region drawRegion(tr.transform(
1780 layer->visibleNonTransparentRegion));
1781 drawRegion.andSelf(bounds);
1782 if (!drawRegion.isEmpty()) {
1783 layersSortedByZ.add(layer);
1784 } else {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001785 // Clear out the HWC layer if this layer was
1786 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001787 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001788 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001789 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001790 } else {
1791 // WM changes displayDevice->layerStack upon sleep/awake.
1792 // Here we make sure we delete the HWC layers even if
1793 // WM changed their layer stack.
1794 hwcLayerDestroyed = layer->destroyHwcLayer(
1795 displayDevice->getHwcDisplayId());
Chia-I Wu83806892017-11-16 10:50:20 -08001796 }
1797
1798 // If a layer is not going to get a release fence because
1799 // it is invisible, but it is also going to release its
1800 // old buffer, add it to the list of layers needing
1801 // fences.
1802 if (hwcLayerDestroyed) {
1803 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1804 mLayersWithQueuedFrames.cend(), layer);
1805 if (found != mLayersWithQueuedFrames.cend()) {
1806 layersNeedingFences.add(layer);
1807 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001808 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001809 });
1810 }
1811 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001812 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001813 displayDevice->undefinedRegion.set(bounds);
1814 displayDevice->undefinedRegion.subtractSelf(
1815 tr.transform(opaqueRegion));
1816 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001817 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001818 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001819}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001820
Romain Guy0147a172017-06-01 13:53:56 -07001821mat4 SurfaceFlinger::computeSaturationMatrix() const {
1822 if (mSaturation == 1.0f) {
1823 return mat4();
1824 }
1825
1826 // Rec.709 luma coefficients
1827 float3 luminance{0.213f, 0.715f, 0.072f};
1828 luminance *= 1.0f - mSaturation;
1829 return mat4(
1830 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1831 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1832 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1833 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1834 );
1835}
1836
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001837// pickColorMode translates a given dataspace into the best available color mode.
1838// Currently only support sRGB and Display-P3.
Peiyong Lina52f0292018-03-14 17:26:31 -07001839ColorMode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Romain Guy54f154a2017-10-24 21:40:32 +01001840 if (mForceNativeColorMode) {
Peiyong Lina52f0292018-03-14 17:26:31 -07001841 return ColorMode::NATIVE;
Romain Guy54f154a2017-10-24 21:40:32 +01001842 }
1843
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001844 switch (dataSpace) {
1845 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1846 // system expects.
1847 case HAL_DATASPACE_UNKNOWN:
1848 case HAL_DATASPACE_SRGB:
1849 case HAL_DATASPACE_V0_SRGB:
Peiyong Lina52f0292018-03-14 17:26:31 -07001850 return ColorMode::SRGB;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001851 break;
1852
1853 case HAL_DATASPACE_DISPLAY_P3:
Peiyong Lina52f0292018-03-14 17:26:31 -07001854 return ColorMode::DISPLAY_P3;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001855 break;
1856
1857 default:
1858 // TODO (courtneygo): Do we want to assert an error here?
1859 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1860 dataSpace);
Peiyong Lina52f0292018-03-14 17:26:31 -07001861 return ColorMode::SRGB;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001862 break;
1863 }
1864}
1865
Romain Guy0147a172017-06-01 13:53:56 -07001866android_dataspace SurfaceFlinger::bestTargetDataSpace(
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001867 android_dataspace a, android_dataspace b, bool hasHdr) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001868 // Only support sRGB and Display-P3 right now.
1869 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1870 return HAL_DATASPACE_DISPLAY_P3;
1871 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001872 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1873 return HAL_DATASPACE_DISPLAY_P3;
1874 }
1875 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1876 return HAL_DATASPACE_DISPLAY_P3;
1877 }
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001878 if (!hasHdr) {
1879 if (a == HAL_DATASPACE_BT2020_PQ || b == HAL_DATASPACE_BT2020_PQ) {
1880 return HAL_DATASPACE_DISPLAY_P3;
1881 }
1882 if (a == HAL_DATASPACE_BT2020_ITU_PQ || b == HAL_DATASPACE_BT2020_ITU_PQ) {
1883 return HAL_DATASPACE_DISPLAY_P3;
1884 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001885 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001886
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001887 return HAL_DATASPACE_V0_SRGB;
1888}
1889
Chia-I Wu30505fb2018-03-26 16:20:31 -07001890void SurfaceFlinger::setUpHWComposer() {
1891 ATRACE_CALL();
1892 ALOGV("setUpHWComposer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08001893
Jesse Hall028dc8f2013-08-20 16:35:32 -07001894 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001895 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1896 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1897 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1898
1899 // If nothing has changed (!dirty), don't recompose.
1900 // If something changed, but we don't currently have any visible layers,
1901 // and didn't when we last did a composition, then skip it this time.
1902 // The second rule does two things:
1903 // - When all layers are removed from a display, we'll emit one black
1904 // frame, then nothing more until we get new layers.
1905 // - When a display is created with a private layer stack, we won't
1906 // emit any black frames until a layer is added to the layer stack.
1907 bool mustRecompose = dirty && !(empty && wasEmpty);
1908
1909 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1910 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1911 mustRecompose ? "doing" : "skipping",
1912 dirty ? "+" : "-",
1913 empty ? "+" : "-",
1914 wasEmpty ? "+" : "-");
1915
Dan Stoza71433162014-02-04 16:22:36 -08001916 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001917
1918 if (mustRecompose) {
1919 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1920 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001921 }
1922
Chia-I Wu30505fb2018-03-26 16:20:31 -07001923 // build the h/w work list
1924 if (CC_UNLIKELY(mGeometryInvalid)) {
1925 mGeometryInvalid = false;
1926 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1927 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1928 const auto hwcId = displayDevice->getHwcDisplayId();
1929 if (hwcId >= 0) {
1930 const Vector<sp<Layer>>& currentLayers(
1931 displayDevice->getVisibleLayersSortedByZ());
1932 for (size_t i = 0; i < currentLayers.size(); i++) {
1933 const auto& layer = currentLayers[i];
1934 if (!layer->hasHwcLayer(hwcId)) {
1935 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
1936 layer->forceClientComposition(hwcId);
1937 continue;
1938 }
1939 }
1940
1941 layer->setGeometry(displayDevice, i);
1942 if (mDebugDisableHWC || mDebugRegion) {
1943 layer->forceClientComposition(hwcId);
1944 }
1945 }
1946 }
1947 }
1948 }
1949
1950
1951 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
1952
1953 // Set the per-frame data
1954 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1955 auto& displayDevice = mDisplays[displayId];
1956 const auto hwcId = displayDevice->getHwcDisplayId();
1957
1958 if (hwcId < 0) {
1959 continue;
1960 }
1961 if (colorMatrix != mPreviousColorMatrix) {
1962 status_t result = getBE().mHwc->setColorTransform(hwcId, colorMatrix);
1963 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1964 "display %zd: %d", displayId, result);
1965 }
1966 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1967 if ((layer->getDataSpace() == HAL_DATASPACE_BT2020_PQ ||
1968 layer->getDataSpace() == HAL_DATASPACE_BT2020_ITU_PQ) &&
1969 !displayDevice->getHdrSupport()) {
1970 layer->forceClientComposition(hwcId);
1971 }
1972
1973 if (layer->getForceClientComposition(hwcId)) {
1974 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1975 layer->setCompositionType(hwcId, HWC2::Composition::Client);
1976 continue;
1977 }
1978
1979 layer->setPerFrameData(displayDevice);
1980 }
1981
1982 if (hasWideColorDisplay) {
1983 ColorMode newColorMode;
1984 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1985
1986 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1987 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace,
1988 displayDevice->getHdrSupport());
1989 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1990 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1991 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1992 }
1993 newColorMode = pickColorMode(newDataSpace);
1994
1995 setActiveColorModeInternal(displayDevice, newColorMode);
1996 }
1997 }
1998
1999 mPreviousColorMatrix = colorMatrix;
2000
Dan Stoza9e56aa02015-11-02 13:00:03 -08002001 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002002 auto& displayDevice = mDisplays[displayId];
2003 if (!displayDevice->isDisplayOn()) {
2004 continue;
2005 }
2006
David Sodman105b7dc2017-11-04 20:28:14 -07002007 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002008 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2009 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002010 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002011}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002012
Mathias Agopiancd60f992012-08-16 16:28:27 -07002013void SurfaceFlinger::doComposition() {
2014 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002015 ALOGV("doComposition");
2016
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002017 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002018 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002019 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002020 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002021 // transform the dirty region into this screen's coordinate space
2022 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002023
2024 // repaint the framebuffer (if needed)
2025 doDisplayComposition(hw, dirtyRegion);
2026
Mathias Agopiancd60f992012-08-16 16:28:27 -07002027 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002028 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002029 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002030 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002031 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002032}
2033
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002034void SurfaceFlinger::postFramebuffer()
2035{
Mathias Agopian841cde52012-03-01 15:44:37 -08002036 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002037 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002038
Mathias Agopiana44b0412011-10-16 18:46:35 -07002039 const nsecs_t now = systemTime();
2040 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002041
Dan Stoza9e56aa02015-11-02 13:00:03 -08002042 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2043 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002044 if (!displayDevice->isDisplayOn()) {
2045 continue;
2046 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002047 const auto hwcId = displayDevice->getHwcDisplayId();
2048 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002049 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002050 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002051 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002052 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002053 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002054 // The layer buffer from the previous frame (if any) is released
2055 // by HWC only when the release fence from this frame (if any) is
2056 // signaled. Always get the release fence from HWC first.
2057 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002058 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002059
2060 // If the layer was client composited in the previous frame, we
2061 // need to merge with the previous client target acquire fence.
2062 // Since we do not track that, always merge with the current
2063 // client target acquire fence when it is available, even though
2064 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002065 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002066 releaseFence = Fence::merge("LayerRelease", releaseFence,
2067 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002068 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002069
David Sodmanb8af7922017-12-21 15:17:55 -08002070 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002071 }
Chia-I Wu83806892017-11-16 10:50:20 -08002072
2073 // We've got a list of layers needing fences, that are disjoint with
2074 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2075 // supply them with the present fence.
2076 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002077 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002078 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002079 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002080 }
2081 }
2082
Dan Stoza9e56aa02015-11-02 13:00:03 -08002083 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002084 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002085 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002086 }
2087
Mathias Agopiana44b0412011-10-16 18:46:35 -07002088 mLastSwapBufferTime = systemTime() - now;
2089 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002090
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002091 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002092 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2093 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2094 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2095 logFrameStats();
2096 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002097 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002098}
2099
Mathias Agopian87baae12012-07-31 12:38:26 -07002100void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002101{
Mathias Agopian841cde52012-03-01 15:44:37 -08002102 ATRACE_CALL();
2103
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002104 // here we keep a copy of the drawing state (that is the state that's
2105 // going to be overwritten by handleTransactionLocked()) outside of
2106 // mStateLock so that the side-effects of the State assignment
2107 // don't happen with mStateLock held (which can cause deadlocks).
2108 State drawingState(mDrawingState);
2109
Mathias Agopianca4d3602011-05-19 15:38:14 -07002110 Mutex::Autolock _l(mStateLock);
2111 const nsecs_t now = systemTime();
2112 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002113
Mathias Agopianca4d3602011-05-19 15:38:14 -07002114 // Here we're guaranteed that some transaction flags are set
2115 // so we can call handleTransactionLocked() unconditionally.
2116 // We call getTransactionFlags(), which will also clear the flags,
2117 // with mStateLock held to guarantee that mCurrentState won't change
2118 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002119
Mathias Agopiane57f2922012-08-09 16:29:12 -07002120 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002121 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002122
Mathias Agopianca4d3602011-05-19 15:38:14 -07002123 mLastTransactionTime = systemTime() - now;
2124 mDebugInTransaction = 0;
2125 invalidateHwcGeometry();
2126 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002127}
2128
Lloyd Pique715a2c12017-12-14 17:18:08 -08002129DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002130 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002131 // Figure out whether the event is for the primary display or an
2132 // external display by matching the Hwc display id against one for a
2133 // connected display. If we did not find a match, we then check what
2134 // displays are not already connected to determine the type. If we don't
2135 // have a connected primary display, we assume the new display is meant to
2136 // be the primary display, and then if we don't have an external display,
2137 // we assume it is that.
2138 const auto primaryDisplayId =
2139 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2140 const auto externalDisplayId =
2141 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2142 if (primaryDisplayId && primaryDisplayId == display) {
2143 return DisplayDevice::DISPLAY_PRIMARY;
2144 } else if (externalDisplayId && externalDisplayId == display) {
2145 return DisplayDevice::DISPLAY_EXTERNAL;
2146 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2147 return DisplayDevice::DISPLAY_PRIMARY;
2148 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2149 return DisplayDevice::DISPLAY_EXTERNAL;
2150 }
2151
2152 return DisplayDevice::DISPLAY_ID_INVALID;
2153}
2154
Lloyd Piqueba04e622017-12-14 17:11:26 -08002155void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2156 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002157 auto displayType = determineDisplayType(event.display, event.connection);
2158 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2159 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2160 continue;
2161 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002162
2163 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2164 ALOGE("External displays are not supported by the vr hardware composer.");
2165 continue;
2166 }
2167
Lloyd Pique715a2c12017-12-14 17:18:08 -08002168 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002169
2170 if (event.connection == HWC2::Connection::Connected) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002171 if (!mBuiltinDisplays[displayType].get()) {
2172 ALOGV("Creating built in display %d", displayType);
2173 mBuiltinDisplays[displayType] = new BBinder();
2174 // All non-virtual displays are currently considered secure.
2175 DisplayDeviceState info(displayType, true);
2176 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2177 "Built-in Screen" : "External Screen";
2178 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
2179 mInterceptor->saveDisplayCreation(info);
2180 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002181 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002182 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002183
Lloyd Piquefcd86612017-12-14 17:15:36 -08002184 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2185 if (idx >= 0) {
2186 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Lloyd Pique4dccc412018-01-22 17:21:36 -08002187 mInterceptor->saveDisplayDeletion(info.displayId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002188 mCurrentState.displays.removeItemsAt(idx);
2189 }
2190 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002191 }
2192
2193 processDisplayChangesLocked();
2194 }
2195
2196 mPendingHotplugEvents.clear();
2197}
2198
Lloyd Pique99d3da52018-01-22 17:48:03 -08002199sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2200 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2201 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
2202 bool hasWideColorSupport = false;
2203 if (hasWideColorDisplay) {
2204 std::vector<ColorMode> modes = getHwComposer().getColorModes(state.type);
2205 for (ColorMode colorMode : modes) {
2206 switch (colorMode) {
2207 case ColorMode::DISPLAY_P3:
2208 case ColorMode::ADOBE_RGB:
2209 case ColorMode::DCI_P3:
2210 hasWideColorSupport = true;
2211 break;
2212 default:
2213 break;
2214 }
2215 }
2216 }
2217
2218 bool hasHdrSupport = false;
2219 std::unique_ptr<HdrCapabilities> hdrCapabilities =
2220 getHwComposer().getHdrCapabilities(state.type);
2221 if (hdrCapabilities) {
2222 const std::vector<int32_t> types = hdrCapabilities->getSupportedHdrTypes();
2223 auto iter = std::find(types.cbegin(), types.cend(), HAL_HDR_HDR10);
2224 hasHdrSupport = iter != types.cend();
2225 }
2226
2227 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2228 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2229
2230 /*
2231 * Create our display's surface
2232 */
2233 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2234 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
2235 renderSurface->setAsync(state.type >= DisplayDevice::DISPLAY_VIRTUAL);
2236 renderSurface->setNativeWindow(nativeWindow.get());
2237 const int displayWidth = renderSurface->queryWidth();
2238 const int displayHeight = renderSurface->queryHeight();
2239
2240 // Make sure that composition can never be stalled by a virtual display
2241 // consumer that isn't processing buffers fast enough. We have to do this
2242 // in two places:
2243 // * Here, in case the display is composed entirely by HWC.
2244 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2245 // window's swap interval in eglMakeCurrent, so they'll override the
2246 // interval we set here.
2247 if (state.type >= DisplayDevice::DISPLAY_VIRTUAL) {
2248 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2249 }
2250
2251 // virtual displays are always considered enabled
2252 auto initialPowerMode = (state.type >= DisplayDevice::DISPLAY_VIRTUAL) ? HWC_POWER_MODE_NORMAL
2253 : HWC_POWER_MODE_OFF;
2254
2255 sp<DisplayDevice> hw =
2256 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2257 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
2258 hasWideColorSupport, hasHdrSupport, initialPowerMode);
2259
2260 if (maxFrameBufferAcquiredBuffers >= 3) {
2261 nativeWindowSurface->preallocateBuffers();
2262 }
2263
2264 ColorMode defaultColorMode = ColorMode::NATIVE;
2265 if (hasWideColorSupport) {
2266 defaultColorMode = ColorMode::SRGB;
2267 }
2268 setActiveColorModeInternal(hw, defaultColorMode);
2269 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
2270 hw->setLayerStack(state.layerStack);
2271 hw->setProjection(state.orientation, state.viewport, state.frame);
2272 hw->setDisplayName(state.displayName);
2273
2274 return hw;
2275}
2276
Lloyd Pique347200f2017-12-14 17:00:15 -08002277void SurfaceFlinger::processDisplayChangesLocked() {
2278 // here we take advantage of Vector's copy-on-write semantics to
2279 // improve performance by skipping the transaction entirely when
2280 // know that the lists are identical
2281 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2282 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2283 if (!curr.isIdenticalTo(draw)) {
2284 mVisibleRegionsDirty = true;
2285 const size_t cc = curr.size();
2286 size_t dc = draw.size();
2287
2288 // find the displays that were removed
2289 // (ie: in drawing state but not in current state)
2290 // also handle displays that changed
2291 // (ie: displays that are in both lists)
2292 for (size_t i = 0; i < dc;) {
2293 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2294 if (j < 0) {
2295 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002296 // Call makeCurrent() on the primary display so we can
2297 // be sure that nothing associated with this display
2298 // is current.
2299 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2300 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2301 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2302 if (hw != nullptr) hw->disconnect(getHwComposer());
2303 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2304 mEventThread->onHotplugReceived(draw[i].type, false);
2305 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002306 } else {
2307 // this display is in both lists. see if something changed.
2308 const DisplayDeviceState& state(curr[j]);
2309 const wp<IBinder>& display(curr.keyAt(j));
2310 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2311 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2312 if (state_binder != draw_binder) {
2313 // changing the surface is like destroying and
2314 // recreating the DisplayDevice, so we just remove it
2315 // from the drawing state, so that it get re-added
2316 // below.
2317 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2318 if (hw != nullptr) hw->disconnect(getHwComposer());
2319 mDisplays.removeItem(display);
2320 mDrawingState.displays.removeItemsAt(i);
2321 dc--;
2322 // at this point we must loop to the next item
2323 continue;
2324 }
2325
2326 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2327 if (disp != nullptr) {
2328 if (state.layerStack != draw[i].layerStack) {
2329 disp->setLayerStack(state.layerStack);
2330 }
2331 if ((state.orientation != draw[i].orientation) ||
2332 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2333 disp->setProjection(state.orientation, state.viewport, state.frame);
2334 }
2335 if (state.width != draw[i].width || state.height != draw[i].height) {
2336 disp->setDisplaySize(state.width, state.height);
2337 }
2338 }
2339 }
2340 ++i;
2341 }
2342
2343 // find displays that were added
2344 // (ie: in current state but not in drawing state)
2345 for (size_t i = 0; i < cc; i++) {
2346 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2347 const DisplayDeviceState& state(curr[i]);
2348
2349 sp<DisplaySurface> dispSurface;
2350 sp<IGraphicBufferProducer> producer;
2351 sp<IGraphicBufferProducer> bqProducer;
2352 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002353 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002354
2355 int32_t hwcId = -1;
2356 if (state.isVirtualDisplay()) {
2357 // Virtual displays without a surface are dormant:
2358 // they have external state (layer stack, projection,
2359 // etc.) but no internal state (i.e. a DisplayDevice).
2360 if (state.surface != nullptr) {
2361 // Allow VR composer to use virtual displays.
2362 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2363 int width = 0;
2364 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2365 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2366 int height = 0;
2367 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2368 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2369 int intFormat = 0;
2370 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2371 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2372 auto format = static_cast<android_pixel_format_t>(intFormat);
2373
2374 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2375 }
2376
2377 // TODO: Plumb requested format back up to consumer
2378
2379 sp<VirtualDisplaySurface> vds =
2380 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2381 bqProducer, bqConsumer,
2382 state.displayName);
2383
2384 dispSurface = vds;
2385 producer = vds;
2386 }
2387 } else {
2388 ALOGE_IF(state.surface != nullptr,
2389 "adding a supported display, but rendering "
2390 "surface is provided (%p), ignoring it",
2391 state.surface.get());
2392
2393 hwcId = state.type;
2394 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2395 producer = bqProducer;
2396 }
2397
2398 const wp<IBinder>& display(curr.keyAt(i));
2399 if (dispSurface != nullptr) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002400 mDisplays.add(display,
2401 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2402 producer));
Lloyd Pique347200f2017-12-14 17:00:15 -08002403 if (!state.isVirtualDisplay()) {
2404 mEventThread->onHotplugReceived(state.type, true);
2405 }
2406 }
2407 }
2408 }
2409 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002410
2411 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002412}
2413
Mathias Agopian87baae12012-07-31 12:38:26 -07002414void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002415{
Dan Stoza7dde5992015-05-22 09:51:44 -07002416 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002417 mCurrentState.traverseInZOrder([](Layer* layer) {
2418 layer->notifyAvailableFrames();
2419 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002420
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002421 /*
2422 * Traversal of the children
2423 * (perform the transaction for each of them if needed)
2424 */
2425
Mathias Agopian3559b072012-08-15 13:46:03 -07002426 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002427 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002428 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002429 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002430
2431 const uint32_t flags = layer->doTransaction(0);
2432 if (flags & Layer::eVisibleRegion)
2433 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002434 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002435 }
2436
2437 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002438 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002439 */
2440
Mathias Agopiane57f2922012-08-09 16:29:12 -07002441 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002442 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002443 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002444 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002445
Mathias Agopian84300952012-11-21 16:02:13 -08002446 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2447 // The transform hint might have changed for some layers
2448 // (either because a display has changed, or because a layer
2449 // as changed).
2450 //
2451 // Walk through all the layers in currentLayers,
2452 // and update their transform hint.
2453 //
2454 // If a layer is visible only on a single display, then that
2455 // display is used to calculate the hint, otherwise we use the
2456 // default display.
2457 //
2458 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2459 // the hint is set before we acquire a buffer from the surface texture.
2460 //
2461 // NOTE: layer transactions have taken place already, so we use their
2462 // drawing state. However, SurfaceFlinger's own transaction has not
2463 // happened yet, so we must use the current state layer list
2464 // (soon to become the drawing state list).
2465 //
2466 sp<const DisplayDevice> disp;
2467 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002468 bool first = true;
2469 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002470 // NOTE: we rely on the fact that layers are sorted by
2471 // layerStack first (so we don't have to traverse the list
2472 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002473 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002474 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002475 currentlayerStack = layerStack;
2476 // figure out if this layerstack is mirrored
2477 // (more than one display) if so, pick the default display,
2478 // if not, pick the only display it's on.
2479 disp.clear();
2480 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2481 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002482 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002483 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002484 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002485 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002486 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002487 break;
2488 }
2489 }
2490 }
2491 }
Chet Haase91d25932013-04-11 15:24:55 -07002492
Robert Carr56a0b9a2017-12-04 16:06:13 -08002493 if (transactionFlags & eDisplayTransactionNeeded) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002494 if (disp == nullptr) {
Robert Carr56a0b9a2017-12-04 16:06:13 -08002495 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2496 // redraw after transform hint changes. See bug 8508397.
2497
2498 // could be null when this layer is using a layerStack
2499 // that is not visible on any display. Also can occur at
2500 // screen off/on times.
2501 disp = getDefaultDisplayDeviceLocked();
2502 }
2503 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08002504 }
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002505 if (disp != nullptr) {
2506 layer->updateTransformHint(disp);
2507 }
Robert Carr2047fae2016-11-28 14:09:09 -08002508
2509 first = false;
2510 });
Mathias Agopian84300952012-11-21 16:02:13 -08002511 }
2512
2513
Mathias Agopian3559b072012-08-15 13:46:03 -07002514 /*
2515 * Perform our own transaction if needed
2516 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002517
2518 if (mLayersAdded) {
2519 mLayersAdded = false;
2520 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002521 mVisibleRegionsDirty = true;
2522 }
2523
2524 // some layers might have been removed, so
2525 // we need to update the regions they're exposing.
2526 if (mLayersRemoved) {
2527 mLayersRemoved = false;
2528 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002529 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002530 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002531 // this layer is not visible anymore
2532 // TODO: we could traverse the tree from front to back and
2533 // compute the actual visible region
2534 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002535 Region visibleReg;
2536 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002537 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002538 }
Robert Carr2047fae2016-11-28 14:09:09 -08002539 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002540 }
2541
2542 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002543
2544 updateCursorAsync();
2545}
2546
2547void SurfaceFlinger::updateCursorAsync()
2548{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002549 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2550 auto& displayDevice = mDisplays[displayId];
2551 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002552 continue;
2553 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002554
2555 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2556 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002557 }
2558 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002559}
2560
2561void SurfaceFlinger::commitTransaction()
2562{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002563 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002564 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002565 for (const auto& l : mLayersPendingRemoval) {
2566 recordBufferingStats(l->getName().string(),
2567 l->getOccupancyHistory(true));
2568 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002569 }
2570 mLayersPendingRemoval.clear();
2571 }
2572
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002573 // If this transaction is part of a window animation then the next frame
2574 // we composite should be considered an animation as well.
2575 mAnimCompositionPending = mAnimTransactionPending;
2576
Mathias Agopian4fec8732012-06-29 14:12:52 -07002577 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002578 mDrawingState.traverseInZOrder([](Layer* layer) {
2579 layer->commitChildList();
2580 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002581 mTransactionPending = false;
2582 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002583 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002584}
2585
Chia-I Wuab0c3192017-08-01 11:29:00 -07002586void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002587 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002588{
Mathias Agopian841cde52012-03-01 15:44:37 -08002589 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002590 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002591
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002592 Region aboveOpaqueLayers;
2593 Region aboveCoveredLayers;
2594 Region dirty;
2595
Mathias Agopian87baae12012-07-31 12:38:26 -07002596 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002597
Robert Carr2047fae2016-11-28 14:09:09 -08002598 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002599 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002600 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002601
Jesse Hall01e29052013-02-19 16:13:35 -08002602 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002603 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002604 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002605
Mathias Agopianab028732010-03-16 16:41:46 -07002606 /*
2607 * opaqueRegion: area of a surface that is fully opaque.
2608 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002609 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002610
2611 /*
2612 * visibleRegion: area of a surface that is visible on screen
2613 * and not fully transparent. This is essentially the layer's
2614 * footprint minus the opaque regions above it.
2615 * Areas covered by a translucent surface are considered visible.
2616 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002617 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002618
2619 /*
2620 * coveredRegion: area of a surface that is covered by all
2621 * visible regions above it (which includes the translucent areas).
2622 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002623 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002624
Jesse Halla8026d22012-09-25 13:25:04 -07002625 /*
2626 * transparentRegion: area of a surface that is hinted to be completely
2627 * transparent. This is only used to tell when the layer has no visible
2628 * non-transparent regions and can be removed from the layer list. It
2629 * does not affect the visibleRegion of this layer or any layers
2630 * beneath it. The hint may not be correct if apps don't respect the
2631 * SurfaceView restrictions (which, sadly, some don't).
2632 */
2633 Region transparentRegion;
2634
Mathias Agopianab028732010-03-16 16:41:46 -07002635
2636 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002637 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002638 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002639 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002640 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002641 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002642 if (!visibleRegion.isEmpty()) {
2643 // Remove the transparent area from the visible region
2644 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002645 if (tr.preserveRects()) {
2646 // transform the transparent region
2647 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002648 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002649 // transformation too complex, can't do the
2650 // transparent region optimization.
2651 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002652 }
Mathias Agopianab028732010-03-16 16:41:46 -07002653 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002654
Mathias Agopianab028732010-03-16 16:41:46 -07002655 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002656 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002657 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002658 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2659 // the opaque region is the layer's footprint
2660 opaqueRegion = visibleRegion;
2661 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002662 }
2663 }
2664
Robert Carre5f4f692018-01-12 13:12:28 -08002665 if (visibleRegion.isEmpty()) {
2666 layer->clearVisibilityRegions();
2667 return;
2668 }
2669
Mathias Agopianab028732010-03-16 16:41:46 -07002670 // Clip the covered region to the visible region
2671 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2672
2673 // Update aboveCoveredLayers for next (lower) layer
2674 aboveCoveredLayers.orSelf(visibleRegion);
2675
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002676 // subtract the opaque region covered by the layers above us
2677 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002678
2679 // compute this layer's dirty region
2680 if (layer->contentDirty) {
2681 // we need to invalidate the whole region
2682 dirty = visibleRegion;
2683 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002684 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002685 layer->contentDirty = false;
2686 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002687 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002688 * the exposed region consists of two components:
2689 * 1) what's VISIBLE now and was COVERED before
2690 * 2) what's EXPOSED now less what was EXPOSED before
2691 *
2692 * note that (1) is conservative, we start with the whole
2693 * visible region but only keep what used to be covered by
2694 * something -- which mean it may have been exposed.
2695 *
2696 * (2) handles areas that were not covered by anything but got
2697 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002698 */
Mathias Agopianab028732010-03-16 16:41:46 -07002699 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002700 const Region oldVisibleRegion = layer->visibleRegion;
2701 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002702 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2703 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002704 }
2705 dirty.subtractSelf(aboveOpaqueLayers);
2706
2707 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002708 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002709
Mathias Agopianab028732010-03-16 16:41:46 -07002710 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002711 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002712
Jesse Halla8026d22012-09-25 13:25:04 -07002713 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002714 layer->setVisibleRegion(visibleRegion);
2715 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002716 layer->setVisibleNonTransparentRegion(
2717 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002718 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002719
Mathias Agopian87baae12012-07-31 12:38:26 -07002720 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002721}
2722
Chia-I Wuab0c3192017-08-01 11:29:00 -07002723void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002724 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002725 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002726 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002727 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002728 }
2729 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002730}
2731
Dan Stoza6b9454d2014-11-07 16:00:59 -08002732bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002733{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002734 ALOGV("handlePageFlip");
2735
Brian Andersond6927fb2016-07-23 23:37:30 -07002736 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002737
Mathias Agopian4fec8732012-06-29 14:12:52 -07002738 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002739 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002740 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002741
2742 // Store the set of layers that need updates. This set must not change as
2743 // buffers are being latched, as this could result in a deadlock.
2744 // Example: Two producers share the same command stream and:
2745 // 1.) Layer 0 is latched
2746 // 2.) Layer 0 gets a new frame
2747 // 2.) Layer 1 gets a new frame
2748 // 3.) Layer 1 is latched.
2749 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2750 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002751 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002752 if (layer->hasQueuedFrame()) {
2753 frameQueued = true;
2754 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002755 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002756 } else {
2757 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002758 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002759 } else {
2760 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002761 }
Robert Carr2047fae2016-11-28 14:09:09 -08002762 });
2763
Dan Stoza9e56aa02015-11-02 13:00:03 -08002764 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002765 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002766 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002767 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002768 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002769 newDataLatched = true;
2770 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002771 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002772
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002773 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002774
2775 // If we will need to wake up at some time in the future to deal with a
2776 // queued frame that shouldn't be displayed during this vsync period, wake
2777 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002778 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002779 signalLayerUpdate();
2780 }
2781
2782 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002783 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002784}
2785
Mathias Agopianad456f92011-01-13 17:53:01 -08002786void SurfaceFlinger::invalidateHwcGeometry()
2787{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002788 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002789}
2790
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002791
Fabien Sanglard830b8472016-11-30 16:35:58 -08002792void SurfaceFlinger::doDisplayComposition(
2793 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002794 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002795{
Dan Stoza71433162014-02-04 16:22:36 -08002796 // We only need to actually compose the display if:
2797 // 1) It is being handled by hardware composer, which may need this to
2798 // keep its virtual display state machine in sync, or
2799 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002800 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002801 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002802 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002803 return;
2804 }
2805
Dan Stoza9e56aa02015-11-02 13:00:03 -08002806 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002807 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002808
2809 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002810 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002811}
2812
Chia-I Wub02087d2017-11-09 10:19:54 -08002813bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002814{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002815 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002816
Chia-I Wub02087d2017-11-09 10:19:54 -08002817 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002818 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002819 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002820
2821 mat4 oldColorMatrix;
David Sodman105b7dc2017-11-04 20:28:14 -07002822 const bool applyColorMatrix = !getBE().mHwc->hasDeviceComposition(hwcId) &&
2823 !getBE().mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002824 if (applyColorMatrix) {
2825 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2826 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2827 }
2828
David Sodman105b7dc2017-11-04 20:28:14 -07002829 bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002830 if (hasClientComposition) {
2831 ALOGV("hasClientComposition");
2832
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002833 android_dataspace outputDataspace = HAL_DATASPACE_UNKNOWN;
Chia-I Wu9a48a8c2018-02-20 14:27:30 -08002834 if (displayDevice->getWideColorSupport() &&
Peiyong Lina52f0292018-03-14 17:26:31 -07002835 displayDevice->getActiveColorMode() == ColorMode::DISPLAY_P3) {
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002836 outputDataspace = HAL_DATASPACE_DISPLAY_P3;
2837 }
2838 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
2839
Chia-I Wu7f402902017-11-09 12:51:10 -08002840 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002841 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002842 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002843 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002844
2845 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002846 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002847 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2848 }
2849 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002850 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002851
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002852 // Never touch the framebuffer if we don't have any framebuffer layers
David Sodman105b7dc2017-11-04 20:28:14 -07002853 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002854 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002855 // when using overlays, we assume a fully transparent framebuffer
2856 // NOTE: we could reduce how much we need to clear, for instance
2857 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002858 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002859 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002860 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002861 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002862 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002863 // we're left with the letterbox region
2864 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002865 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002866
2867 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002868 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002869
Mathias Agopianb9494d52012-04-18 02:28:45 -07002870 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002871 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002872 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002873 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002874 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002875 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002876
Dan Stoza9e56aa02015-11-02 13:00:03 -08002877 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002878 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002879 // scissor on the main display. It should never be needed
2880 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002881 const Rect& bounds(displayDevice->getBounds());
2882 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002883 if (scissor != bounds) {
2884 // scissor doesn't match the screen's dimensions, so we
2885 // need to clear everything outside of it and enable
2886 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002887
Mathias Agopianf45c5102012-10-24 16:29:17 -07002888 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002889 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002890 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002891 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002892 }
2893 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002894 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002895
Mathias Agopian85d751c2012-08-29 16:59:24 -07002896 /*
2897 * and then, render the layers targeted at the framebuffer
2898 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002899
Dan Stoza9e56aa02015-11-02 13:00:03 -08002900 ALOGV("Rendering client layers");
2901 const Transform& displayTransform = displayDevice->getTransform();
2902 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002903 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002904 bool firstLayer = true;
2905 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002906 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002907 displayTransform.transform(layer->visibleRegion)));
2908 ALOGV("Layer: %s", layer->getName().string());
2909 ALOGV(" Composition type: %s",
2910 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002911 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002912 switch (layer->getCompositionType(hwcId)) {
2913 case HWC2::Composition::Cursor:
2914 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002915 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002916 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002917 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002918 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002919 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002920 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002921 // never clear the very first layer since we're
2922 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002923 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002924 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002925 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002926 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002927 case HWC2::Composition::Client: {
chaviwa76b2712017-09-20 12:02:26 -07002928 layer->draw(renderArea, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002929 break;
2930 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002931 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002932 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002933 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002934 } else {
2935 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002936 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002937 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002938 }
2939 } else {
2940 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002941 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002942 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002943 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002944 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07002945 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002946 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002947 }
2948 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002949
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002950 if (applyColorMatrix) {
2951 getRenderEngine().setupColorTransform(oldColorMatrix);
2952 }
2953
Mathias Agopianf45c5102012-10-24 16:29:17 -07002954 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002955 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002956 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002957}
2958
Fabien Sanglard830b8472016-11-30 16:35:58 -08002959void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2960 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08002961 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07002962 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002963}
2964
Dan Stoza7d89d062015-04-30 13:29:25 -07002965status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002966 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002967 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002968 const sp<Layer>& lbc,
2969 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002970{
Dan Stoza7d89d062015-04-30 13:29:25 -07002971 // add this layer to the current state list
2972 {
2973 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002974 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002975 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2976 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002977 return NO_MEMORY;
2978 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002979 if (parent == nullptr) {
2980 mCurrentState.layersSortedByZ.add(lbc);
2981 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08002982 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002983 ALOGE("addClientLayer called with a removed parent");
2984 return NAME_NOT_FOUND;
2985 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002986 parent->addChild(lbc);
2987 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002988
Dan Stoza101d8dc2018-02-27 15:42:25 -08002989 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
Dan Stoza0a0158c2018-03-16 13:38:54 -07002990 // TODO (b/74616334): Change this back to a fatal assert once the leak is fixed
2991 ALOGE_IF(mGraphicBufferProducerList.size() > mMaxGraphicBufferProducerListSize,
2992 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
2993 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize,
2994 mNumLayers);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002995 mLayersAdded = true;
2996 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002997 }
2998
Mathias Agopian96f08192010-06-02 23:28:45 -07002999 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003000 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003001
Dan Stoza7d89d062015-04-30 13:29:25 -07003002 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003003}
3004
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003005status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003006 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003007 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3008}
Robert Carr7f9b8992017-03-10 11:08:39 -08003009
chaviwca27f252018-02-06 16:46:39 -08003010status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3011 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003012 if (layer->isPendingRemoval()) {
3013 return NO_ERROR;
3014 }
3015
Robert Carr1f0a16a2016-10-24 16:27:39 -07003016 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003017 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003018 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003019 if (topLevelOnly) {
3020 return NO_ERROR;
3021 }
3022
Chia-I Wu98f1c102017-05-30 14:54:08 -07003023 sp<Layer> ancestor = p;
3024 while (ancestor->getParent() != nullptr) {
3025 ancestor = ancestor->getParent();
3026 }
3027 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3028 ALOGE("removeLayer called with a layer whose parent has been removed");
3029 return NAME_NOT_FOUND;
3030 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003031
3032 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003033 } else {
3034 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003035 }
3036
Robert Carr136e2f62017-02-08 17:54:29 -08003037 // As a matter of normal operation, the LayerCleaner will produce a second
3038 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3039 // so we will succeed in promoting it, but it's already been removed
3040 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3041 // otherwise something has gone wrong and we are leaking the layer.
3042 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003043 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3044 layer->getName().string(),
3045 (p != nullptr) ? p->getName().string() : "no-parent");
3046 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003047 } else if (index < 0) {
3048 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003049 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003050
Chia-I Wuc6657022017-08-15 11:18:17 -07003051 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003052 mLayersPendingRemoval.add(layer);
3053 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003054 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003055 setTransactionFlags(eTransactionNeeded);
3056 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003057}
3058
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003059uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003060 return android_atomic_release_load(&mTransactionFlags);
3061}
3062
Mathias Agopian3f844832013-08-07 21:24:32 -07003063uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003064 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3065}
3066
Mathias Agopian3f844832013-08-07 21:24:32 -07003067uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003068 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
3069 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003070 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003071 }
3072 return old;
3073}
3074
chaviwca27f252018-02-06 16:46:39 -08003075bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3076 for (const ComposerState& state : states) {
3077 // Here we need to check that the interface we're given is indeed
3078 // one of our own. A malicious client could give us a nullptr
3079 // IInterface, or one of its own or even one of our own but a
3080 // different type. All these situations would cause us to crash.
3081 if (state.client == nullptr) {
3082 return true;
3083 }
3084
3085 sp<IBinder> binder = IInterface::asBinder(state.client);
3086 if (binder == nullptr) {
3087 return true;
3088 }
3089
3090 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3091 return true;
3092 }
3093 }
3094 return false;
3095}
3096
Mathias Agopian8b33f032012-07-24 20:43:54 -07003097void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003098 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003099 const Vector<DisplayState>& displays,
3100 uint32_t flags)
3101{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003102 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003103 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003104 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003105
chaviwca27f252018-02-06 16:46:39 -08003106 if (containsAnyInvalidClientState(states)) {
3107 return;
3108 }
3109
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003110 if (flags & eAnimation) {
3111 // For window updates that are part of an animation we must wait for
3112 // previous animation "frames" to be handled.
3113 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003114 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003115 if (CC_UNLIKELY(err != NO_ERROR)) {
3116 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003117 // caller after a few seconds.
3118 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3119 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003120 mAnimTransactionPending = false;
3121 break;
3122 }
3123 }
3124 }
3125
chaviwca27f252018-02-06 16:46:39 -08003126 for (const DisplayState& display : displays) {
3127 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003128 }
3129
chaviwca27f252018-02-06 16:46:39 -08003130 for (const ComposerState& state : states) {
3131 transactionFlags |= setClientStateLocked(state);
3132 }
3133
3134 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3135 // as destroyed should only occur after setting all other states. This is to allow for a
3136 // child re-parent to happen before marking its original parent as destroyed (which would
3137 // then mark the child as destroyed).
3138 for (const ComposerState& state : states) {
3139 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003140 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003141
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003142 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3143 // anyway. This can be used as a flush mechanism for previous async transactions.
3144 // Empty animation transaction can be used to simulate back-pressure, so also force a
3145 // transaction for empty animation transactions.
3146 if (transactionFlags == 0 &&
3147 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003148 transactionFlags = eTransactionNeeded;
3149 }
3150
Mathias Agopian386aa982011-11-07 21:58:03 -08003151 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003152 if (mInterceptor->isEnabled()) {
3153 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003154 }
Irvel468051e2016-06-13 16:44:44 -07003155
Mathias Agopian386aa982011-11-07 21:58:03 -08003156 // this triggers the transaction
3157 setTransactionFlags(transactionFlags);
3158
3159 // if this is a synchronous transaction, wait for it to take effect
3160 // before returning.
3161 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003162 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003163 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003164 if (flags & eAnimation) {
3165 mAnimTransactionPending = true;
3166 }
3167 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003168 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3169 if (CC_UNLIKELY(err != NO_ERROR)) {
3170 // just in case something goes wrong in SF, return to the
3171 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003172 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3173 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003174 break;
3175 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003176 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003177 }
3178}
3179
Mathias Agopiane57f2922012-08-09 16:29:12 -07003180uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3181{
Jesse Hall9a143922012-10-04 16:29:19 -07003182 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3183 if (dpyIdx < 0)
3184 return 0;
3185
Mathias Agopiane57f2922012-08-09 16:29:12 -07003186 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003187 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003188 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003189 const uint32_t what = s.what;
3190 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003191 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003192 disp.surface = s.surface;
3193 flags |= eDisplayTransactionNeeded;
3194 }
3195 }
3196 if (what & DisplayState::eLayerStackChanged) {
3197 if (disp.layerStack != s.layerStack) {
3198 disp.layerStack = s.layerStack;
3199 flags |= eDisplayTransactionNeeded;
3200 }
3201 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003202 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003203 if (disp.orientation != s.orientation) {
3204 disp.orientation = s.orientation;
3205 flags |= eDisplayTransactionNeeded;
3206 }
3207 if (disp.frame != s.frame) {
3208 disp.frame = s.frame;
3209 flags |= eDisplayTransactionNeeded;
3210 }
3211 if (disp.viewport != s.viewport) {
3212 disp.viewport = s.viewport;
3213 flags |= eDisplayTransactionNeeded;
3214 }
3215 }
Michael Lentine47e45402014-07-18 15:34:25 -07003216 if (what & DisplayState::eDisplaySizeChanged) {
3217 if (disp.width != s.width) {
3218 disp.width = s.width;
3219 flags |= eDisplayTransactionNeeded;
3220 }
3221 if (disp.height != s.height) {
3222 disp.height = s.height;
3223 flags |= eDisplayTransactionNeeded;
3224 }
3225 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003226 }
3227 return flags;
3228}
3229
chaviwca27f252018-02-06 16:46:39 -08003230uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3231 const layer_state_t& s = composerState.state;
3232 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3233
Mathias Agopian13127d82013-03-05 17:47:11 -08003234 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003235 if (layer == nullptr) {
3236 return 0;
3237 }
3238
3239 if (layer->isPendingRemoval()) {
3240 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3241 return 0;
3242 }
3243
3244 uint32_t flags = 0;
3245
3246 const uint32_t what = s.what;
3247 bool geometryAppliesWithResize =
3248 what & layer_state_t::eGeometryAppliesWithResize;
3249 if (what & layer_state_t::ePositionChanged) {
3250 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3251 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003252 }
chaviw8b3871a2017-11-01 17:41:01 -07003253 }
3254 if (what & layer_state_t::eLayerChanged) {
3255 // NOTE: index needs to be calculated before we update the state
3256 const auto& p = layer->getParent();
3257 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003258 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003259 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003260 mCurrentState.layersSortedByZ.removeAt(idx);
3261 mCurrentState.layersSortedByZ.add(layer);
3262 // we need traversal (state changed)
3263 // AND transaction (list changed)
3264 flags |= eTransactionNeeded|eTraversalNeeded;
3265 }
chaviw8b3871a2017-11-01 17:41:01 -07003266 } else {
3267 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003268 flags |= eTransactionNeeded|eTraversalNeeded;
3269 }
3270 }
chaviw8b3871a2017-11-01 17:41:01 -07003271 }
3272 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003273 // NOTE: index needs to be calculated before we update the state
3274 const auto& p = layer->getParent();
3275 if (p == nullptr) {
3276 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3277 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3278 mCurrentState.layersSortedByZ.removeAt(idx);
3279 mCurrentState.layersSortedByZ.add(layer);
3280 // we need traversal (state changed)
3281 // AND transaction (list changed)
3282 flags |= eTransactionNeeded|eTraversalNeeded;
3283 }
3284 } else {
3285 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3286 flags |= eTransactionNeeded|eTraversalNeeded;
3287 }
chaviw8b3871a2017-11-01 17:41:01 -07003288 }
3289 }
3290 if (what & layer_state_t::eSizeChanged) {
3291 if (layer->setSize(s.w, s.h)) {
3292 flags |= eTraversalNeeded;
3293 }
3294 }
3295 if (what & layer_state_t::eAlphaChanged) {
3296 if (layer->setAlpha(s.alpha))
3297 flags |= eTraversalNeeded;
3298 }
3299 if (what & layer_state_t::eColorChanged) {
3300 if (layer->setColor(s.color))
3301 flags |= eTraversalNeeded;
3302 }
3303 if (what & layer_state_t::eMatrixChanged) {
3304 if (layer->setMatrix(s.matrix))
3305 flags |= eTraversalNeeded;
3306 }
3307 if (what & layer_state_t::eTransparentRegionChanged) {
3308 if (layer->setTransparentRegionHint(s.transparentRegion))
3309 flags |= eTraversalNeeded;
3310 }
3311 if (what & layer_state_t::eFlagsChanged) {
3312 if (layer->setFlags(s.flags, s.mask))
3313 flags |= eTraversalNeeded;
3314 }
3315 if (what & layer_state_t::eCropChanged) {
3316 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3317 flags |= eTraversalNeeded;
3318 }
3319 if (what & layer_state_t::eFinalCropChanged) {
3320 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3321 flags |= eTraversalNeeded;
3322 }
3323 if (what & layer_state_t::eLayerStackChanged) {
3324 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3325 // We only allow setting layer stacks for top level layers,
3326 // everything else inherits layer stack from its parent.
3327 if (layer->hasParent()) {
3328 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3329 layer->getName().string());
3330 } else if (idx < 0) {
3331 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3332 "that also does not appear in the top level layer list. Something"
3333 " has gone wrong.", layer->getName().string());
3334 } else if (layer->setLayerStack(s.layerStack)) {
3335 mCurrentState.layersSortedByZ.removeAt(idx);
3336 mCurrentState.layersSortedByZ.add(layer);
3337 // we need traversal (state changed)
3338 // AND transaction (list changed)
3339 flags |= eTransactionNeeded|eTraversalNeeded;
3340 }
3341 }
3342 if (what & layer_state_t::eDeferTransaction) {
3343 if (s.barrierHandle != nullptr) {
3344 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3345 } else if (s.barrierGbp != nullptr) {
3346 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3347 if (authenticateSurfaceTextureLocked(gbp)) {
3348 const auto& otherLayer =
3349 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3350 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3351 } else {
3352 ALOGE("Attempt to defer transaction to to an"
3353 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003354 }
3355 }
chaviw8b3871a2017-11-01 17:41:01 -07003356 // We don't trigger a traversal here because if no other state is
3357 // changed, we don't want this to cause any more work
3358 }
3359 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003360 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003361 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003362 if (!hadParent) {
3363 mCurrentState.layersSortedByZ.remove(layer);
3364 }
chaviw8b3871a2017-11-01 17:41:01 -07003365 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003366 }
chaviw8b3871a2017-11-01 17:41:01 -07003367 }
3368 if (what & layer_state_t::eReparentChildren) {
3369 if (layer->reparentChildren(s.reparentHandle)) {
3370 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003371 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003372 }
chaviw8b3871a2017-11-01 17:41:01 -07003373 if (what & layer_state_t::eDetachChildren) {
3374 layer->detachChildren();
3375 }
3376 if (what & layer_state_t::eOverrideScalingModeChanged) {
3377 layer->setOverrideScalingMode(s.overrideScalingMode);
3378 // We don't trigger a traversal here because if no other state is
3379 // changed, we don't want this to cause any more work
3380 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003381 return flags;
3382}
3383
chaviwca27f252018-02-06 16:46:39 -08003384void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3385 const layer_state_t& state = composerState.state;
3386 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3387
3388 sp<Layer> layer(client->getLayerUser(state.surface));
3389 if (layer == nullptr) {
3390 return;
3391 }
3392
3393 if (layer->isPendingRemoval()) {
3394 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3395 return;
3396 }
3397
3398 if (state.what & layer_state_t::eDestroySurface) {
3399 removeLayerLocked(mStateLock, layer);
3400 }
3401}
3402
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003403status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003404 const String8& name,
3405 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003406 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003407 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003408 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003409{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003410 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003411 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003412 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003413 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003414 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003415
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003416 status_t result = NO_ERROR;
3417
3418 sp<Layer> layer;
3419
Cody Northropbc755282017-03-31 12:00:08 -06003420 String8 uniqueName = getUniqueLayerName(name);
3421
Mathias Agopian3165cc22012-08-08 19:42:09 -07003422 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3423 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003424 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003425 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003426 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003427
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003428 break;
chaviw13fdc492017-06-27 12:40:18 -07003429 case ISurfaceComposerClient::eFXSurfaceColor:
3430 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003431 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003432 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003433 break;
3434 default:
3435 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003436 break;
3437 }
3438
Dan Stoza7d89d062015-04-30 13:29:25 -07003439 if (result != NO_ERROR) {
3440 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003441 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003442
Chia-I Wuab0c3192017-08-01 11:29:00 -07003443 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3444 // TODO b/64227542
3445 if (windowType == 441731) {
3446 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3447 layer->setPrimaryDisplayOnly();
3448 }
3449
Albert Chaulk479c60c2017-01-27 14:21:34 -05003450 layer->setInfo(windowType, ownerUid);
3451
Robert Carr1f0a16a2016-10-24 16:27:39 -07003452 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003453 if (result != NO_ERROR) {
3454 return result;
3455 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003456 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003457
3458 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003459 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003460}
3461
Cody Northropbc755282017-03-31 12:00:08 -06003462String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3463{
3464 bool matchFound = true;
3465 uint32_t dupeCounter = 0;
3466
3467 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3468 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3469
3470 // Loop over layers until we're sure there is no matching name
3471 while (matchFound) {
3472 matchFound = false;
3473 mDrawingState.traverseInZOrder([&](Layer* layer) {
3474 if (layer->getName() == uniqueName) {
3475 matchFound = true;
3476 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3477 }
3478 });
3479 }
3480
3481 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3482
3483 return uniqueName;
3484}
3485
David Sodman0c69cad2017-08-21 12:12:51 -07003486status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003487 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3488 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003489{
3490 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003491 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003492 case PIXEL_FORMAT_TRANSPARENT:
3493 case PIXEL_FORMAT_TRANSLUCENT:
3494 format = PIXEL_FORMAT_RGBA_8888;
3495 break;
3496 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003497 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003498 break;
3499 }
3500
David Sodman0c69cad2017-08-21 12:12:51 -07003501 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3502 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003503 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003504 *handle = layer->getHandle();
3505 *gbp = layer->getProducer();
3506 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003507 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003508
David Sodman0c69cad2017-08-21 12:12:51 -07003509 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003510 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003511}
3512
chaviw13fdc492017-06-27 12:40:18 -07003513status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003514 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003515 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003516{
chaviw13fdc492017-06-27 12:40:18 -07003517 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003518 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003519 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003520}
3521
Mathias Agopianac9fa422013-02-11 16:40:36 -08003522status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003523{
Robert Carr9524cb32017-02-13 11:32:32 -08003524 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003525 status_t err = NO_ERROR;
3526 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003527 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003528 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003529 err = removeLayer(l);
3530 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3531 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003532 }
3533 return err;
3534}
3535
Mathias Agopian13127d82013-03-05 17:47:11 -08003536status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003537{
Mathias Agopian67106042013-03-14 19:18:13 -07003538 // called by ~LayerCleaner() when all references to the IBinder (handle)
3539 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003540 sp<Layer> l = layer.promote();
3541 if (l == nullptr) {
3542 // The layer has already been removed, carry on
3543 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003544 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003545 // If we have a parent, then we can continue to live as long as it does.
3546 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003547}
3548
Mathias Agopianb60314a2012-04-10 22:09:54 -07003549// ---------------------------------------------------------------------------
3550
Andy McFadden13a082e2012-08-24 10:16:42 -07003551void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003552 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003553 Vector<ComposerState> state;
3554 Vector<DisplayState> displays;
3555 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003556 d.what = DisplayState::eDisplayProjectionChanged |
3557 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003558 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003559 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003560 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003561 d.frame.makeInvalid();
3562 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003563 d.width = 0;
3564 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003565 displays.add(d);
3566 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003567 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3568 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003569
David Sodman105b7dc2017-11-04 20:28:14 -07003570 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003571 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003572 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003573
Brian Andersond0010582017-03-07 13:20:31 -08003574 // Use phase of 0 since phase is not known.
3575 // Use latency of 0, which will snap to the ideal latency.
3576 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003577}
3578
3579void SurfaceFlinger::initializeDisplays() {
3580 class MessageScreenInitialized : public MessageBase {
3581 SurfaceFlinger* flinger;
3582 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003583 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003584 virtual bool handler() {
3585 flinger->onInitializeDisplays();
3586 return true;
3587 }
3588 };
3589 sp<MessageBase> msg = new MessageScreenInitialized(this);
3590 postMessageAsync(msg); // we may be called from main thread, use async message
3591}
3592
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003593void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003594 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003595 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3596 this);
3597 int32_t type = hw->getDisplayType();
3598 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003599
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003600 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003601 return;
3602 }
3603
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003604 hw->setPowerMode(mode);
3605 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3606 ALOGW("Trying to set power mode for virtual display");
3607 return;
3608 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003609
Lloyd Pique4dccc412018-01-22 17:21:36 -08003610 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003611 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003612 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3613 if (idx < 0) {
3614 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3615 return;
3616 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003617 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003618 }
3619
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003620 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003621 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003622 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003623 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3624 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003625 // FIXME: eventthread only knows about the main display right now
3626 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003627 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003628 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003629
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003630 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003631 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003632 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003633
3634 struct sched_param param = {0};
3635 param.sched_priority = 1;
3636 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3637 ALOGW("Couldn't set SCHED_FIFO on display on");
3638 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003639 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003640 // Turn off the display
3641 struct sched_param param = {0};
3642 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3643 ALOGW("Couldn't set SCHED_OTHER on display off");
3644 }
3645
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003646 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3647 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003648 disableHardwareVsync(true); // also cancels any in-progress resync
3649
Mathias Agopiancde87a32012-09-13 14:09:01 -07003650 // FIXME: eventthread only knows about the main display right now
3651 mEventThread->onScreenReleased();
3652 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003653
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003654 getHwComposer().setPowerMode(type, mode);
3655 mVisibleRegionsDirty = true;
3656 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003657 } else if (mode == HWC_POWER_MODE_DOZE ||
3658 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003659 // Update display while dozing
3660 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003661 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3662 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003663 // FIXME: eventthread only knows about the main display right now
3664 mEventThread->onScreenAcquired();
3665 resyncToHardwareVsync(true);
3666 }
3667 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3668 // Leave display going to doze
3669 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3670 disableHardwareVsync(true); // also cancels any in-progress resync
3671 // FIXME: eventthread only knows about the main display right now
3672 mEventThread->onScreenReleased();
3673 }
3674 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003675 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003676 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003677 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003678 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003679}
3680
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003681void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3682 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003683 SurfaceFlinger& mFlinger;
3684 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003685 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003686 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003687 MessageSetPowerMode(SurfaceFlinger& flinger,
3688 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3689 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003690 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003691 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003692 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003693 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003694 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003695 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003696 ALOGW("Attempt to set power mode = %d for virtual display",
3697 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003698 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003699 mFlinger.setPowerModeInternal(
3700 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003701 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003702 return true;
3703 }
3704 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003705 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003706 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003707}
3708
3709// ---------------------------------------------------------------------------
3710
Lloyd Pique755e3192018-01-31 16:46:15 -08003711status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3712 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003713 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003714
Mathias Agopianbd115332013-04-18 16:41:04 -07003715 IPCThreadState* ipc = IPCThreadState::self();
3716 const int pid = ipc->getCallingPid();
3717 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003718
Mathias Agopianbd115332013-04-18 16:41:04 -07003719 if ((uid != AID_SHELL) &&
3720 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003721 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003722 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003723 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003724 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003725 // (this would indicate SF is stuck, but we want to be able to
3726 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003727 status_t err = mStateLock.timedLock(s2ns(1));
3728 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003729 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003730 result.appendFormat(
3731 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3732 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003733 }
3734
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003735 bool dumpAll = true;
3736 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003737 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003738
3739 if (asProto) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003740 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviwa3d7bd32017-11-03 09:41:53 -07003741 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3742 dumpAll = false;
3743 }
3744
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003745 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003746 if ((index < numArgs) &&
3747 (args[index] == String16("--list"))) {
3748 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003749 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003750 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003751 }
3752
3753 if ((index < numArgs) &&
3754 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003755 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003756 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003757 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003758 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003759
3760 if ((index < numArgs) &&
3761 (args[index] == String16("--latency-clear"))) {
3762 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003763 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003764 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003765 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003766
3767 if ((index < numArgs) &&
3768 (args[index] == String16("--dispsync"))) {
3769 index++;
3770 mPrimaryDispSync.dump(result);
3771 dumpAll = false;
3772 }
Dan Stozab90cf072015-03-05 11:05:59 -08003773
3774 if ((index < numArgs) &&
3775 (args[index] == String16("--static-screen"))) {
3776 index++;
3777 dumpStaticScreenStats(result);
3778 dumpAll = false;
3779 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003780
3781 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003782 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003783 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003784 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003785 dumpAll = false;
3786 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003787
3788 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3789 index++;
3790 dumpWideColorInfo(result);
3791 dumpAll = false;
3792 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003793
3794 if ((index < numArgs) &&
3795 (args[index] == String16("--enable-layer-stats"))) {
3796 index++;
3797 mLayerStats.enable();
3798 dumpAll = false;
3799 }
3800
3801 if ((index < numArgs) &&
3802 (args[index] == String16("--disable-layer-stats"))) {
3803 index++;
3804 mLayerStats.disable();
3805 dumpAll = false;
3806 }
3807
3808 if ((index < numArgs) &&
3809 (args[index] == String16("--clear-layer-stats"))) {
3810 index++;
3811 mLayerStats.clear();
3812 dumpAll = false;
3813 }
3814
3815 if ((index < numArgs) &&
3816 (args[index] == String16("--dump-layer-stats"))) {
3817 index++;
3818 mLayerStats.dump(result);
3819 dumpAll = false;
3820 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003821 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003822
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003823 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003824 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003825 }
3826
Mathias Agopian9795c422009-08-26 16:36:26 -07003827 if (locked) {
3828 mStateLock.unlock();
3829 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003830 }
3831 write(fd, result.string(), result.size());
3832 return NO_ERROR;
3833}
3834
Dan Stozac7014012014-02-14 15:03:43 -08003835void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3836 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003837{
Robert Carr2047fae2016-11-28 14:09:09 -08003838 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003839 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003840 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003841}
3842
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003843void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003844 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003845{
3846 String8 name;
3847 if (index < args.size()) {
3848 name = String8(args[index]);
3849 index++;
3850 }
3851
David Sodman105b7dc2017-11-04 20:28:14 -07003852 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003853 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003854 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003855
3856 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003857 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003858 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003859 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003860 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003861 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003862 }
Robert Carr2047fae2016-11-28 14:09:09 -08003863 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003864 }
3865}
3866
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003867void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003868 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003869{
3870 String8 name;
3871 if (index < args.size()) {
3872 name = String8(args[index]);
3873 index++;
3874 }
3875
Robert Carr2047fae2016-11-28 14:09:09 -08003876 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003877 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003878 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003879 }
Robert Carr2047fae2016-11-28 14:09:09 -08003880 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003881
Svetoslavd85084b2014-03-20 10:28:31 -07003882 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003883}
3884
Jamie Gennis6547ff42013-07-16 20:12:42 -07003885// This should only be called from the main thread. Otherwise it would need
3886// the lock and should use mCurrentState rather than mDrawingState.
3887void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003888 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003889 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003890 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003891
3892 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3893}
3894
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003895void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003896{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003897 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003898
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003899 if (isLayerTripleBufferingDisabled())
3900 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003901
3902 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003903 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003904 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003905 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003906 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3907 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003908 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003909}
3910
Dan Stozab90cf072015-03-05 11:05:59 -08003911void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3912{
3913 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003914 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3915 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003916 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003917 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003918 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3919 b + 1, bucketTimeSec, percent);
3920 }
David Sodman4a36e932017-11-07 14:29:47 -08003921 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003922 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003923 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003924 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08003925 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003926}
3927
Dan Stozae77c7662016-05-13 11:37:28 -07003928void SurfaceFlinger::recordBufferingStats(const char* layerName,
3929 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08003930 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
3931 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07003932 for (const auto& segment : history) {
3933 if (!segment.usedThirdBuffer) {
3934 stats.twoBufferTime += segment.totalTime;
3935 }
3936 if (segment.occupancyAverage < 1.0f) {
3937 stats.doubleBufferedTime += segment.totalTime;
3938 } else if (segment.occupancyAverage < 2.0f) {
3939 stats.tripleBufferedTime += segment.totalTime;
3940 }
3941 ++stats.numSegments;
3942 stats.totalTime += segment.totalTime;
3943 }
3944}
3945
Brian Andersond6927fb2016-07-23 23:37:30 -07003946void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3947 result.appendFormat("Layer frame timestamps:\n");
3948
3949 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3950 const size_t count = currentLayers.size();
3951 for (size_t i=0 ; i<count ; i++) {
3952 currentLayers[i]->dumpFrameEvents(result);
3953 }
3954}
3955
Dan Stozae77c7662016-05-13 11:37:28 -07003956void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3957 result.append("Buffering stats:\n");
3958 result.append(" [Layer name] <Active time> <Two buffer> "
3959 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08003960 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07003961 typedef std::tuple<std::string, float, float, float> BufferTuple;
3962 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08003963 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07003964 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08003965 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07003966 if (stats.numSegments == 0) {
3967 continue;
3968 }
3969 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3970 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3971 stats.totalTime;
3972 float doubleBufferRatio = static_cast<float>(
3973 stats.doubleBufferedTime) / stats.totalTime;
3974 float tripleBufferRatio = static_cast<float>(
3975 stats.tripleBufferedTime) / stats.totalTime;
3976 sorted.insert({activeTime, {name, twoBufferRatio,
3977 doubleBufferRatio, tripleBufferRatio}});
3978 }
3979 for (const auto& sortedPair : sorted) {
3980 float activeTime = sortedPair.first;
3981 const BufferTuple& values = sortedPair.second;
3982 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3983 std::get<0>(values).c_str(), activeTime,
3984 std::get<1>(values), std::get<2>(values),
3985 std::get<3>(values));
3986 }
3987 result.append("\n");
3988}
3989
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003990void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3991 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Romain Guy54f154a2017-10-24 21:40:32 +01003992 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003993
3994 // TODO: print out if wide-color mode is active or not
3995
3996 for (size_t d = 0; d < mDisplays.size(); d++) {
3997 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3998 int32_t hwcId = displayDevice->getHwcDisplayId();
3999 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4000 continue;
4001 }
4002
4003 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004004 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004005 for (auto&& mode : modes) {
4006 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4007 }
4008
Peiyong Lina52f0292018-03-14 17:26:31 -07004009 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004010 result.appendFormat(" Current color mode: %s (%d)\n",
4011 decodeColorMode(currentMode).c_str(), currentMode);
4012 }
4013 result.append("\n");
4014}
4015
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004016LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004017 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004018 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4019 const State& state = useDrawing ? mDrawingState : mCurrentState;
4020 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004021 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004022 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004023 });
4024
4025 return layersProto;
4026}
4027
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004028LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4029 LayersProto layersProto;
4030
4031 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
4032 SizeProto* resolution = layersProto.mutable_resolution();
4033 resolution->set_w(displayDevice->getWidth());
4034 resolution->set_h(displayDevice->getHeight());
4035
4036 mDrawingState.traverseInZOrder([&](Layer* layer) {
4037 if (!layer->visibleRegion.isEmpty() &&
4038 layer->getBE().mHwcLayers.count(hwcId)) {
4039 LayerProto* layerProto = layersProto.add_layers();
4040 layer->writeToProto(layerProto, hwcId);
4041 }
4042 });
4043
4044 return layersProto;
4045}
4046
Mathias Agopian74d211a2013-04-22 16:55:35 +02004047void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4048 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004049{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004050 bool colorize = false;
4051 if (index < args.size()
4052 && (args[index] == String16("--color"))) {
4053 colorize = true;
4054 index++;
4055 }
4056
4057 Colorizer colorizer(colorize);
4058
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004059 // figure out if we're stuck somewhere
4060 const nsecs_t now = systemTime();
4061 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4062 const nsecs_t inTransaction(mDebugInTransaction);
4063 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4064 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4065
4066 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004067 * Dump library configuration.
4068 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004069
4070 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004071 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004072 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004073 appendSfConfigString(result);
4074 appendUiConfigString(result);
4075 appendGuiConfigString(result);
4076 result.append("\n");
4077
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004078 result.append("\nWide-Color information:\n");
4079 dumpWideColorInfo(result);
4080
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004081 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004082 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004083 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004084 result.append(SyncFeatures::getInstance().toString());
4085 result.append("\n");
4086
David Sodman105b7dc2017-11-04 20:28:14 -07004087 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004088
Andy McFadden41d67d72014-04-25 16:58:34 -07004089 colorizer.bold(result);
4090 result.append("DispSync configuration: ");
4091 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07004092 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004093 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08004094 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004095 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004096 result.append("\n");
4097
Dan Stozab90cf072015-03-05 11:05:59 -08004098 // Dump static screen stats
4099 result.append("\n");
4100 dumpStaticScreenStats(result);
4101 result.append("\n");
4102
Dan Stozae77c7662016-05-13 11:37:28 -07004103 dumpBufferingStats(result);
4104
Andy McFadden4803b742012-09-24 19:07:20 -07004105 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004106 * Dump the visible layer list
4107 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004108 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004109 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004110 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4111 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004112 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004113
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004114 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004115 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004116 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004117
4118 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004119 * Dump Display state
4120 */
4121
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004122 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004123 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004124 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004125 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4126 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004127 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004128 }
4129
4130 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004131 * Dump SurfaceFlinger global state
4132 */
4133
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004134 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004135 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004136 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004137
Mathias Agopian888c8222012-08-04 21:10:38 -07004138 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004139 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004140
David Sodmanbc815282017-11-05 18:57:52 -08004141 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004142
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004143 if (hw) {
4144 hw->undefinedRegion.dump(result, "undefinedRegion");
4145 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4146 hw->getOrientation(), hw->isDisplayOn());
4147 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004148 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004149 " last eglSwapBuffers() time: %f us\n"
4150 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004151 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004152 " refresh-rate : %f fps\n"
4153 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004154 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004155 " gpu_to_cpu_unsupported : %d\n"
4156 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004157 mLastSwapBufferTime/1000.0,
4158 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004159 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004160 1e9 / activeConfig->getVsyncPeriod(),
4161 activeConfig->getDpiX(),
4162 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004163 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004164
Mathias Agopian74d211a2013-04-22 16:55:35 +02004165 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004166 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004167
Mathias Agopian74d211a2013-04-22 16:55:35 +02004168 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004169 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004170
4171 /*
4172 * VSYNC state
4173 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004174 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004175 result.append("\n");
4176
4177 /*
4178 * HWC layer minidump
4179 */
4180 for (size_t d = 0; d < mDisplays.size(); d++) {
4181 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4182 int32_t hwcId = displayDevice->getHwcDisplayId();
4183 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4184 continue;
4185 }
4186
4187 result.appendFormat("Display %d HWC layers:\n", hwcId);
4188 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004189 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004190 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004191 });
Dan Stozae22aec72016-08-01 13:20:59 -07004192 result.append("\n");
4193 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004194
4195 /*
4196 * Dump HWComposer state
4197 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004198 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004199 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004200 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004201 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004202 result.appendFormat(" h/w composer %s\n",
4203 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004204 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004205
4206 /*
4207 * Dump gralloc state
4208 */
4209 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4210 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004211
4212 /*
4213 * Dump VrFlinger state if in use.
4214 */
4215 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4216 result.append("VrFlinger state:\n");
4217 result.append(mVrFlinger->Dump().c_str());
4218 result.append("\n");
4219 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004220}
4221
Mathias Agopian13127d82013-03-05 17:47:11 -08004222const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004223SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004224 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004225 wp<IBinder> dpy;
4226 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4227 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4228 dpy = mDisplays.keyAt(i);
4229 break;
4230 }
4231 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004232 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004233 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4234 // Just use the primary display so we have something to return
4235 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4236 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004237 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004238}
4239
Keun young Park63f165f2012-08-31 10:53:36 -07004240bool SurfaceFlinger::startDdmConnection()
4241{
4242 void* libddmconnection_dso =
4243 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4244 if (!libddmconnection_dso) {
4245 return false;
4246 }
4247 void (*DdmConnection_start)(const char* name);
4248 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004249 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004250 if (!DdmConnection_start) {
4251 dlclose(libddmconnection_dso);
4252 return false;
4253 }
4254 (*DdmConnection_start)(getServiceName());
4255 return true;
4256}
4257
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004258status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004259 switch (code) {
4260 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004261 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004262 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004263 case CLEAR_ANIMATION_FRAME_STATS:
4264 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004265 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004266 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004267 case ENABLE_VSYNC_INJECTIONS:
4268 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004269 {
4270 // codes that require permission check
4271 IPCThreadState* ipc = IPCThreadState::self();
4272 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004273 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004274 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004275 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004276 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004277 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004278 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004279 break;
4280 }
Robert Carr1db73f62016-12-21 12:58:51 -08004281 /*
4282 * Calling setTransactionState is safe, because you need to have been
4283 * granted a reference to Client* and Handle* to do anything with it.
4284 *
4285 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4286 */
4287 case SET_TRANSACTION_STATE:
4288 case CREATE_SCOPED_CONNECTION:
4289 {
4290 return OK;
4291 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004292 case CAPTURE_SCREEN:
4293 {
4294 // codes that require permission check
4295 IPCThreadState* ipc = IPCThreadState::self();
4296 const int pid = ipc->getCallingPid();
4297 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004298 if ((uid != AID_GRAPHICS) &&
4299 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004300 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004301 return PERMISSION_DENIED;
4302 }
4303 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004304 }
chaviwa76b2712017-09-20 12:02:26 -07004305 case CAPTURE_LAYERS: {
4306 IPCThreadState* ipc = IPCThreadState::self();
4307 const int pid = ipc->getCallingPid();
4308 const int uid = ipc->getCallingUid();
4309 if ((uid != AID_GRAPHICS) &&
4310 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4311 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4312 return PERMISSION_DENIED;
4313 }
4314 break;
4315 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004316 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004317 return OK;
4318}
4319
4320status_t SurfaceFlinger::onTransact(
4321 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4322{
4323 status_t credentialCheck = CheckTransactCodeCredentials(code);
4324 if (credentialCheck != OK) {
4325 return credentialCheck;
4326 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004327
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004328 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4329 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004330 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004331 IPCThreadState* ipc = IPCThreadState::self();
4332 const int uid = ipc->getCallingUid();
4333 if (CC_UNLIKELY(uid != AID_SYSTEM
4334 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004335 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004336 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004337 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004338 return PERMISSION_DENIED;
4339 }
4340 int n;
4341 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004342 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004343 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004344 return NO_ERROR;
4345 case 1002: // SHOW_UPDATES
4346 n = data.readInt32();
4347 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004348 invalidateHwcGeometry();
4349 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004350 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004351 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004352 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004353 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004354 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004355 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004356 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004357 setTransactionFlags(
4358 eTransactionNeeded|
4359 eDisplayTransactionNeeded|
4360 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004361 return NO_ERROR;
4362 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004363 case 1006:{ // send empty update
4364 signalRefresh();
4365 return NO_ERROR;
4366 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004367 case 1008: // toggle use of hw composer
4368 n = data.readInt32();
4369 mDebugDisableHWC = n ? 1 : 0;
4370 invalidateHwcGeometry();
4371 repaintEverything();
4372 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004373 case 1009: // toggle use of transform hint
4374 n = data.readInt32();
4375 mDebugDisableTransformHint = n ? 1 : 0;
4376 invalidateHwcGeometry();
4377 repaintEverything();
4378 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004379 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004380 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004381 reply->writeInt32(0);
4382 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004383 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004384 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004385 return NO_ERROR;
4386 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004387 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004388 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004389 return NO_ERROR;
4390 }
4391 case 1014: {
4392 // daltonize
4393 n = data.readInt32();
4394 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004395 case 1:
4396 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4397 break;
4398 case 2:
4399 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4400 break;
4401 case 3:
4402 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4403 break;
4404 default:
4405 mDaltonizer.setType(ColorBlindnessType::None);
4406 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004407 }
4408 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004409 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004410 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004411 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004412 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004413 invalidateHwcGeometry();
4414 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004415 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004416 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004417 case 1015: {
4418 // apply a color matrix
4419 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004420 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004421 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004422 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004423 for (size_t j = 0; j < 4; j++) {
4424 mColorMatrix[i][j] = data.readFloat();
4425 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004426 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004427 } else {
4428 mColorMatrix = mat4();
4429 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004430
4431 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4432 // the division by w in the fragment shader
4433 float4 lastRow(transpose(mColorMatrix)[3]);
4434 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4435 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4436 }
4437
Alan Viverette9c5a3332013-09-12 20:04:35 -07004438 invalidateHwcGeometry();
4439 repaintEverything();
4440 return NO_ERROR;
4441 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004442 // This is an experimental interface
4443 // Needs to be shifted to proper binder interface when we productize
4444 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004445 n = data.readInt32();
4446 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004447 return NO_ERROR;
4448 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004449 case 1017: {
4450 n = data.readInt32();
4451 mForceFullDamage = static_cast<bool>(n);
4452 return NO_ERROR;
4453 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004454 case 1018: { // Modify Choreographer's phase offset
4455 n = data.readInt32();
4456 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4457 return NO_ERROR;
4458 }
4459 case 1019: { // Modify SurfaceFlinger's phase offset
4460 n = data.readInt32();
4461 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4462 return NO_ERROR;
4463 }
Irvel468051e2016-06-13 16:44:44 -07004464 case 1020: { // Layer updates interceptor
4465 n = data.readInt32();
4466 if (n) {
4467 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004468 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004469 }
4470 else{
4471 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004472 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004473 }
4474 return NO_ERROR;
4475 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004476 case 1021: { // Disable HWC virtual displays
4477 n = data.readInt32();
4478 mUseHwcVirtualDisplays = !n;
4479 return NO_ERROR;
4480 }
Romain Guy0147a172017-06-01 13:53:56 -07004481 case 1022: { // Set saturation boost
4482 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4483
4484 invalidateHwcGeometry();
4485 repaintEverything();
4486 return NO_ERROR;
4487 }
Romain Guy54f154a2017-10-24 21:40:32 +01004488 case 1023: { // Set native mode
4489 mForceNativeColorMode = data.readInt32() == 1;
4490
4491 invalidateHwcGeometry();
4492 repaintEverything();
4493 return NO_ERROR;
4494 }
4495 case 1024: { // Is wide color gamut rendering/color management supported?
4496 reply->writeBool(hasWideColorDisplay);
4497 return NO_ERROR;
4498 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004499 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004500 n = data.readInt32();
4501 if (n) {
4502 ALOGV("LayerTracing enabled");
4503 mTracing.enable();
4504 doTracing("tracing.enable");
4505 reply->writeInt32(NO_ERROR);
4506 } else {
4507 ALOGV("LayerTracing disabled");
4508 status_t err = mTracing.disable();
4509 reply->writeInt32(err);
4510 }
4511 return NO_ERROR;
4512 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004513 case 1026: { // Get layer tracing status
4514 reply->writeBool(mTracing.isEnabled());
4515 return NO_ERROR;
4516 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004517 }
4518 }
4519 return err;
4520}
4521
Steven Thomas6d8110b2017-08-31 18:24:21 -07004522void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004523 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004524 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004525}
4526
Steven Thomas6d8110b2017-08-31 18:24:21 -07004527void SurfaceFlinger::repaintEverything() {
4528 ConditionalLock _l(mStateLock,
4529 std::this_thread::get_id() != mMainThreadId);
4530 repaintEverythingLocked();
4531}
4532
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004533// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4534class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004535public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004536 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4537 ~WindowDisconnector() {
4538 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004539 }
4540
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004541private:
4542 ANativeWindow* mWindow;
4543 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004544};
4545
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004546status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4547 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4548 int32_t minLayerZ, int32_t maxLayerZ,
4549 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004550 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004551 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004552
chaviwa76b2712017-09-20 12:02:26 -07004553 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4554
4555 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004556 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4557
chaviwa76b2712017-09-20 12:02:26 -07004558 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4559
4560 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4561 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004562 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004563}
4564
4565status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004566 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004567 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004568 ATRACE_CALL();
4569
4570 class LayerRenderArea : public RenderArea {
4571 public:
Robert Carr578038f2018-03-09 12:25:24 -08004572 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4573 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
4574 : RenderArea(reqHeight, reqWidth),
4575 mLayer(layer),
4576 mCrop(crop),
4577 mFlinger(flinger),
4578 mChildrenOnly(childrenOnly) {}
chaviwa76b2712017-09-20 12:02:26 -07004579 Rect getBounds() const override {
4580 const Layer::State& layerState(mLayer->getDrawingState());
4581 return Rect(layerState.active.w, layerState.active.h);
4582 }
4583 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4584 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4585 bool isSecure() const override { return false; }
4586 bool needsFiltering() const override { return false; }
Robert Carr578038f2018-03-09 12:25:24 -08004587 const Transform& getTransform() const { return mTransform; }
4588
4589 class ReparentForDrawing {
4590 public:
4591 const sp<Layer>& oldParent;
4592 const sp<Layer>& newParent;
4593
4594 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4595 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004596 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004597 }
Robert Carr15eae092018-03-23 13:43:53 -07004598 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004599 };
4600
4601 void render(std::function<void()> drawLayers) override {
4602 if (!mChildrenOnly) {
4603 mTransform = mLayer->getTransform().inverse();
4604 drawLayers();
4605 } else {
4606 Rect bounds = getBounds();
4607 screenshotParentLayer =
4608 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4609 bounds.getWidth(), bounds.getHeight(), 0);
4610
4611 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4612 drawLayers();
4613 }
4614 }
chaviwa76b2712017-09-20 12:02:26 -07004615
chaviw7206d492017-11-10 16:16:12 -08004616 Rect getSourceCrop() const override {
4617 if (mCrop.isEmpty()) {
4618 return getBounds();
4619 } else {
4620 return mCrop;
4621 }
4622 }
chaviwa76b2712017-09-20 12:02:26 -07004623 bool getWideColorSupport() const override { return false; }
Peiyong Lina52f0292018-03-14 17:26:31 -07004624 ColorMode getActiveColorMode() const override { return ColorMode::NATIVE; }
chaviwa76b2712017-09-20 12:02:26 -07004625
4626 private:
chaviw7206d492017-11-10 16:16:12 -08004627 const sp<Layer> mLayer;
4628 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004629
4630 // In the "childrenOnly" case we reparent the children to a screenshot
4631 // layer which has no properties set and which does not draw.
4632 sp<ContainerLayer> screenshotParentLayer;
4633 Transform mTransform;
4634
4635 SurfaceFlinger* mFlinger;
4636 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004637 };
4638
4639 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4640 auto parent = layerHandle->owner.promote();
4641
chaviw7206d492017-11-10 16:16:12 -08004642 if (parent == nullptr || parent->isPendingRemoval()) {
4643 ALOGE("captureLayers called with a removed parent");
4644 return NAME_NOT_FOUND;
4645 }
4646
Robert Carr578038f2018-03-09 12:25:24 -08004647 const int uid = IPCThreadState::self()->getCallingUid();
4648 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4649 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4650 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4651 return PERMISSION_DENIED;
4652 }
4653
chaviw7206d492017-11-10 16:16:12 -08004654 Rect crop(sourceCrop);
4655 if (sourceCrop.width() <= 0) {
4656 crop.left = 0;
4657 crop.right = parent->getCurrentState().active.w;
4658 }
4659
4660 if (sourceCrop.height() <= 0) {
4661 crop.top = 0;
4662 crop.bottom = parent->getCurrentState().active.h;
4663 }
4664
4665 int32_t reqWidth = crop.width() * frameScale;
4666 int32_t reqHeight = crop.height() * frameScale;
4667
Robert Carr578038f2018-03-09 12:25:24 -08004668 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004669
Robert Carr578038f2018-03-09 12:25:24 -08004670 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004671 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4672 if (!layer->isVisible()) {
4673 return;
Robert Carr578038f2018-03-09 12:25:24 -08004674 } else if (childrenOnly && layer == parent.get()) {
4675 return;
chaviwa76b2712017-09-20 12:02:26 -07004676 }
4677 visitor(layer);
4678 });
4679 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004680 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004681}
4682
4683status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4684 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004685 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004686 bool useIdentityTransform) {
4687 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004688
chaviwa76b2712017-09-20 12:02:26 -07004689 renderArea.updateDimensions();
4690
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004691 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4692 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4693 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4694 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004695
4696 // This mutex protects syncFd and captureResult for communication of the return values from the
4697 // main thread back to this Binder thread
4698 std::mutex captureMutex;
4699 std::condition_variable captureCondition;
4700 std::unique_lock<std::mutex> captureLock(captureMutex);
4701 int syncFd = -1;
4702 std::optional<status_t> captureResult;
4703
Robert Carr03480e22018-01-04 16:02:06 -08004704 const int uid = IPCThreadState::self()->getCallingUid();
4705 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4706
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004707 sp<LambdaMessage> message = new LambdaMessage([&]() {
4708 // If there is a refresh pending, bug out early and tell the binder thread to try again
4709 // after the refresh.
4710 if (mRefreshPending) {
4711 ATRACE_NAME("Skipping screenshot for now");
4712 std::unique_lock<std::mutex> captureLock(captureMutex);
4713 captureResult = std::make_optional<status_t>(EAGAIN);
4714 captureCondition.notify_one();
4715 return;
4716 }
4717
4718 status_t result = NO_ERROR;
4719 int fd = -1;
4720 {
4721 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004722 renderArea.render([&]() {
4723 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4724 useIdentityTransform, forSystem, &fd);
4725 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004726 }
4727
4728 {
4729 std::unique_lock<std::mutex> captureLock(captureMutex);
4730 syncFd = fd;
4731 captureResult = std::make_optional<status_t>(result);
4732 captureCondition.notify_one();
4733 }
4734 });
4735
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004736 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004737 if (result == NO_ERROR) {
4738 captureCondition.wait(captureLock, [&]() { return captureResult; });
4739 while (*captureResult == EAGAIN) {
4740 captureResult.reset();
4741 result = postMessageAsync(message);
4742 if (result != NO_ERROR) {
4743 return result;
4744 }
4745 captureCondition.wait(captureLock, [&]() { return captureResult; });
4746 }
4747 result = *captureResult;
4748 }
4749
4750 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004751 sync_wait(syncFd, -1);
4752 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004753 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004754
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004755 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004756}
4757
chaviwa76b2712017-09-20 12:02:26 -07004758void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4759 TraverseLayersFunction traverseLayers, bool yswap,
4760 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004761 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004762
Lloyd Pique144e1162017-12-20 16:44:52 -08004763 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004764
4765 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004766 const auto raWidth = renderArea.getWidth();
4767 const auto raHeight = renderArea.getHeight();
4768
4769 const auto reqWidth = renderArea.getReqWidth();
4770 const auto reqHeight = renderArea.getReqHeight();
4771 Rect sourceCrop = renderArea.getSourceCrop();
4772
4773 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4774 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004775
Dan Stozac1879002014-05-22 15:59:05 -07004776 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004777 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004778 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004779 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004780 }
4781
4782 // ensure that sourceCrop is inside screen
4783 if (sourceCrop.left < 0) {
4784 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4785 }
chaviwa76b2712017-09-20 12:02:26 -07004786 if (sourceCrop.right > raWidth) {
4787 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004788 }
4789 if (sourceCrop.top < 0) {
4790 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4791 }
chaviwa76b2712017-09-20 12:02:26 -07004792 if (sourceCrop.bottom > raHeight) {
4793 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004794 }
4795
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004796 android_dataspace outputDataspace = HAL_DATASPACE_UNKNOWN;
Chia-I Wu9a48a8c2018-02-20 14:27:30 -08004797 if (renderArea.getWideColorSupport() &&
Peiyong Lina52f0292018-03-14 17:26:31 -07004798 renderArea.getActiveColorMode() == ColorMode::DISPLAY_P3) {
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004799 outputDataspace = HAL_DATASPACE_DISPLAY_P3;
4800 }
4801 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Romain Guy88d37dd2017-05-26 17:57:05 -07004802
Mathias Agopian180f10d2013-04-10 22:55:41 -07004803 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004804 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004805
4806 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004807 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4808 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004809 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004810
4811 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004812 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004813
chaviwa76b2712017-09-20 12:02:26 -07004814 traverseLayers([&](Layer* layer) {
4815 if (filtering) layer->setFiltering(true);
David Sodmandc5e0622018-01-05 23:10:57 -08004816 layer->drawNow(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004817 if (filtering) layer->setFiltering(false);
4818 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004819}
4820
chaviwa76b2712017-09-20 12:02:26 -07004821status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4822 TraverseLayersFunction traverseLayers,
4823 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004824 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08004825 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07004826 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004827 ATRACE_CALL();
4828
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004829 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004830
4831 traverseLayers([&](Layer* layer) {
4832 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4833 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004834
Robert Carr03480e22018-01-04 16:02:06 -08004835 // We allow the system server to take screenshots of secure layers for
4836 // use in situations like the Screen-rotation animation and place
4837 // the impetus on WindowManager to not persist them.
4838 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004839 ALOGW("FB is protected: PERMISSION_DENIED");
4840 return PERMISSION_DENIED;
4841 }
4842
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004843 // this binds the given EGLImage as a framebuffer for the
4844 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08004845 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08004846 if (bufferBond.getStatus() != NO_ERROR) {
4847 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004848 return INVALID_OPERATION;
4849 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004850
Dan Stozaabcda352017-06-01 14:37:39 -07004851 // this will in fact render into our dequeued buffer
4852 // via an FBO, which means we didn't have to create
4853 // an EGLSurface and therefore we're not
4854 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004855 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004856
Dan Stozaabcda352017-06-01 14:37:39 -07004857 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08004858 getRenderEngine().finish();
4859 *outSyncFd = -1;
4860
chaviwa76b2712017-09-20 12:02:26 -07004861 const auto reqWidth = renderArea.getReqWidth();
4862 const auto reqHeight = renderArea.getReqHeight();
4863
Dan Stozaabcda352017-06-01 14:37:39 -07004864 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4865 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004866 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004867 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08004868 } else {
4869 base::unique_fd syncFd = getRenderEngine().flush();
4870 if (syncFd < 0) {
4871 getRenderEngine().finish();
4872 }
4873 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07004874 }
4875
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004876 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004877}
4878
Mathias Agopiand5556842013-09-19 17:08:37 -07004879void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07004880 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004881 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004882 for (size_t y = 0; y < h; y++) {
4883 uint32_t const* p = (uint32_t const*)vaddr + y * s;
4884 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004885 if (p[x] != 0xFF000000) return;
4886 }
4887 }
chaviwa76b2712017-09-20 12:02:26 -07004888 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07004889
Robert Carr2047fae2016-11-28 14:09:09 -08004890 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07004891 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004892 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07004893 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4894 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
4895 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
4896 static_cast<float>(state.color.a));
4897 i++;
4898 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07004899 }
4900}
4901
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004902// ---------------------------------------------------------------------------
4903
Dan Stoza412903f2017-04-27 13:42:17 -07004904void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4905 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004906}
4907
Dan Stoza412903f2017-04-27 13:42:17 -07004908void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4909 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004910}
4911
chaviwa76b2712017-09-20 12:02:26 -07004912void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
4913 int32_t maxLayerZ,
4914 const LayerVector::Visitor& visitor) {
4915 // We loop through the first level of layers without traversing,
4916 // as we need to interpret min/max layer Z in the top level Z space.
4917 for (const auto& layer : mDrawingState.layersSortedByZ) {
4918 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4919 continue;
4920 }
4921 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08004922 // relative layers are traversed in Layer::traverseInZOrder
4923 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07004924 continue;
4925 }
4926 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01004927 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4928 return;
4929 }
chaviwa76b2712017-09-20 12:02:26 -07004930 if (!layer->isVisible()) {
4931 return;
4932 }
4933 visitor(layer);
4934 });
4935 }
4936}
4937
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004938}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004939
Chia-I Wu30505fb2018-03-26 16:20:31 -07004940
Mathias Agopian3f844832013-08-07 21:24:32 -07004941#if defined(__gl_h_)
4942#error "don't include gl/gl.h in this file"
4943#endif
4944
4945#if defined(__gl2_h_)
4946#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08004947#endif