blob: a27cc3dd57ae58ef3468633ad36984813717b803 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060040#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070041#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070042#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043
Jamie Gennis1a4d8832012-08-02 20:11:05 -070044#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070045#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080047#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080048#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070049
50#include <ui/GraphicBufferAllocator.h>
51#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080053
Mathias Agopiancde87a32012-09-13 14:09:01 -070054#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080055#include <utils/String8.h>
56#include <utils/String16.h>
57#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070058#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080059#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060
Mathias Agopian921e6ac2012-07-23 23:11:29 -070061#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070062#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063
Robert Carr578038f2018-03-09 12:25:24 -080064#include "BufferLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020065#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080066#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020067#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080068#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080069#include "DdmConnection.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070070#include "DispSync.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "DisplayDevice.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070072#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080073#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
Robert Carr578038f2018-03-09 12:25:24 -080078#include "clz.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Steven Thomasb02664d2017-07-26 18:48:28 -070080#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070081#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070082#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070083#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084
Mathias Agopianff2ed702013-09-01 21:36:12 -070085#include "Effects/Daltonizer.h"
86
Mathias Agopian875d8e12013-06-07 15:35:48 -070087#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070088#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070089
Jiyong Park4b20c2e2017-01-14 19:45:11 +090090#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090091#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090092
chaviw1d044282017-09-27 12:19:28 -070093#include <layerproto/LayerProtoParser.h>
94
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080095#define DISPLAY_COUNT 1
96
Mathias Agopianfee2b462013-07-03 12:34:01 -070097/*
98 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
99 * black pixels.
100 */
101#define DEBUG_SCREENSHOTS false
102
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800103namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700104
Jaesoo Lee43518572017-01-23 19:03:16 +0900105using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900106using namespace android::hardware::configstore::V1_0;
107
Steven Thomasb02664d2017-07-26 18:48:28 -0700108namespace {
109class ConditionalLock {
110public:
111 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
112 if (lock) {
113 mMutex.lock();
114 }
115 }
116 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
117private:
118 Mutex& mMutex;
119 bool mLocked;
120};
121} // namespace anonymous
122
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800123// ---------------------------------------------------------------------------
124
Mathias Agopian99b49842011-06-27 16:05:52 -0700125const String16 sHardwareTest("android.permission.HARDWARE_TEST");
126const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
127const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
128const String16 sDump("android.permission.DUMP");
129
130// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800131int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
132int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700133int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700134bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800135uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800136bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800137bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800138int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800139// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600140bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700141
Kalle Raitaa099a242017-01-11 11:17:29 -0800142
143std::string getHwcServiceName() {
144 char value[PROPERTY_VALUE_MAX] = {};
145 property_get("debug.sf.hwc_service_name", value, "default");
146 ALOGI("Using HWComposer service: '%s'", value);
147 return std::string(value);
148}
149
150bool useTrebleTestingOverride() {
151 char value[PROPERTY_VALUE_MAX] = {};
152 property_get("debug.sf.treble_testing_override", value, "false");
153 ALOGI("Treble testing override: '%s'", value);
154 return std::string(value) == "true";
155}
156
Lloyd Pique99d3da52018-01-22 17:48:03 -0800157NativeWindowSurface::~NativeWindowSurface() = default;
158
159namespace impl {
160
161class NativeWindowSurface final : public android::NativeWindowSurface {
162public:
163 static std::unique_ptr<android::NativeWindowSurface> create(
164 const sp<IGraphicBufferProducer>& producer) {
165 return std::make_unique<NativeWindowSurface>(producer);
166 }
167
168 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
169 : surface(new Surface(producer, false)) {}
170
171 ~NativeWindowSurface() override = default;
172
173private:
174 sp<ANativeWindow> getNativeWindow() const override { return surface; }
175
176 void preallocateBuffers() override { surface->allocateBuffers(); }
177
178 sp<Surface> surface;
179};
180
181} // namespace impl
182
David Sodmanbc815282017-11-05 18:57:52 -0800183SurfaceFlingerBE::SurfaceFlingerBE()
184 : mHwcServiceName(getHwcServiceName()),
185 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800186 mFrameBuckets(),
187 mTotalTime(0),
188 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800189 mComposerSequenceId(0) {
190}
191
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800192SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800193 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800194 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700195 mTransactionPending(false),
196 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700197 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700198 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700199 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800200 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800201 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800202 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800203 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800204 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800205 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700206 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700207 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700208 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700209 mDebugInSwapBuffers(0),
210 mLastSwapBufferTime(0),
211 mDebugInTransaction(0),
212 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700213 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700214 mForceFullDamage(false),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000215 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700216 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700217 mHWVsyncAvailable(false),
Romain Guya9638732017-06-01 12:05:21 -0700218 mHasColorMatrix(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800219 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800220 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700221 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800222 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800223 mCreateBufferQueue(&BufferQueue::createBufferQueue),
224 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800225
226SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800227 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800228
229 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
230 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
231
232 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
233 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
234
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800235 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
236 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800237
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700238 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
239 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
240
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700241 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
242 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
243
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800244 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
245 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
246
Steven Thomas050b2c82017-03-06 11:45:16 -0800247 // Vr flinger is only enabled on Daydream ready devices.
248 useVrFlinger = getBool< ISurfaceFlingerConfigs,
249 &ISurfaceFlingerConfigs::useVrFlinger>(false);
250
Fabien Sanglard1971b632017-03-10 14:50:03 -0800251 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
252 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
253
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600254 hasWideColorDisplay =
255 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
256
David Sodman99974d22017-11-28 12:04:33 -0800257 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700258
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800259 // debugging stuff...
260 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700261
Mathias Agopianb4b17302013-03-20 18:36:41 -0700262 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700263 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700264
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800265 property_get("debug.sf.showupdates", value, "0");
266 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700267
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700268 property_get("debug.sf.ddms", value, "0");
269 mDebugDDMS = atoi(value);
270 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700271 if (!startDdmConnection()) {
272 // start failed, and DDMS debugging not enabled
273 mDebugDDMS = 0;
274 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700275 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700276 ALOGI_IF(mDebugRegion, "showupdates enabled");
277 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700278
279 property_get("debug.sf.disable_backpressure", value, "0");
280 mPropagateBackpressure = !atoi(value);
281 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700282
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800283 property_get("debug.sf.enable_hwc_vds", value, "0");
284 mUseHwcVirtualDisplays = atoi(value);
285 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800286
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800287 property_get("ro.sf.disable_triple_buffer", value, "1");
288 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800289 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700290
Dan Stoza0a0158c2018-03-16 13:38:54 -0700291 // TODO (b/74616334): Reduce the default value once we isolate the leak
292 const size_t defaultListSize = 4 * MAX_LAYERS;
293 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
294 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
295
Romain Guy11d63f42017-07-20 12:47:14 -0700296 // We should be reading 'persist.sys.sf.color_saturation' here
297 // but since /data may be encrypted, we need to wait until after vold
298 // comes online to attempt to read the property. The property is
299 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800300
301 if (useTrebleTestingOverride()) {
302 // Without the override SurfaceFlinger cannot connect to HIDL
303 // services that are not listed in the manifests. Considered
304 // deriving the setting from the set service name, but it
305 // would be brittle if the name that's not 'default' is used
306 // for production purposes later on.
307 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
308 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800309}
310
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800311void SurfaceFlinger::onFirstRef()
312{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800313 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800314}
315
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800316SurfaceFlinger::~SurfaceFlinger()
317{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800318}
319
Dan Stozac7014012014-02-14 15:03:43 -0800320void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800321{
322 // the window manager died on us. prepare its eulogy.
323
Andy McFadden13a082e2012-08-24 10:16:42 -0700324 // restore initial conditions (default device unblank, etc)
325 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800326
327 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700328 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800329}
330
Robert Carr1db73f62016-12-21 12:58:51 -0800331static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700332 status_t err = client->initCheck();
333 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800334 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800335 }
Robert Carr1db73f62016-12-21 12:58:51 -0800336 return nullptr;
337}
338
339sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
340 return initClient(new Client(this));
341}
342
343sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
344 const sp<IGraphicBufferProducer>& gbp) {
345 if (authenticateSurfaceTexture(gbp) == false) {
346 return nullptr;
347 }
348 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
349 if (layer == nullptr) {
350 return nullptr;
351 }
352
353 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800354}
355
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700356sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
357 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700358{
359 class DisplayToken : public BBinder {
360 sp<SurfaceFlinger> flinger;
361 virtual ~DisplayToken() {
362 // no more references, this display must be terminated
363 Mutex::Autolock _l(flinger->mStateLock);
364 flinger->mCurrentState.displays.removeItem(this);
365 flinger->setTransactionFlags(eDisplayTransactionNeeded);
366 }
367 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700368 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700369 : flinger(flinger) {
370 }
371 };
372
373 sp<BBinder> token = new DisplayToken(this);
374
375 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700376 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700377 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700378 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800379 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700380 return token;
381}
382
Jesse Hall6c913be2013-08-08 12:15:49 -0700383void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
384 Mutex::Autolock _l(mStateLock);
385
386 ssize_t idx = mCurrentState.displays.indexOfKey(display);
387 if (idx < 0) {
388 ALOGW("destroyDisplay: invalid display token");
389 return;
390 }
391
392 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
393 if (!info.isVirtualDisplay()) {
394 ALOGE("destroyDisplay called for non-virtual display");
395 return;
396 }
Lloyd Pique4dccc412018-01-22 17:21:36 -0800397 mInterceptor->saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700398 mCurrentState.displays.removeItemsAt(idx);
399 setTransactionFlags(eDisplayTransactionNeeded);
400}
401
Mathias Agopiane57f2922012-08-09 16:29:12 -0700402sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700403 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700404 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800405 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700406 }
Jesse Hall692c7232012-11-08 15:41:56 -0800407 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700408}
409
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800410void SurfaceFlinger::bootFinished()
411{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700412 if (mStartPropertySetThread->join() != NO_ERROR) {
413 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800414 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800415 const nsecs_t now = systemTime();
416 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000417 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700418
419 // wait patiently for the window manager death
420 const String16 name("window");
421 sp<IBinder> window(defaultServiceManager()->getService(name));
422 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700423 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700424 }
425
Steven Thomas050b2c82017-03-06 11:45:16 -0800426 if (mVrFlinger) {
427 mVrFlinger->OnBootFinished();
428 }
429
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700430 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700431 // formerly we would just kill the process, but we now ask it to exit so it
432 // can choose where to stop the animation.
433 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700434
435 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
436 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
437 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700438
Thierry Strudel2924d012017-08-14 15:19:37 -0700439 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700440 readPersistentProperties();
441 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700442 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800443}
444
Mathias Agopian3f844832013-08-07 21:24:32 -0700445void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700446 class MessageDestroyGLTexture : public MessageBase {
Lloyd Pique144e1162017-12-20 16:44:52 -0800447 RE::RenderEngine& engine;
Mathias Agopian3f844832013-08-07 21:24:32 -0700448 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700449 public:
Lloyd Pique144e1162017-12-20 16:44:52 -0800450 MessageDestroyGLTexture(RE::RenderEngine& engine, uint32_t texture)
451 : engine(engine), texture(texture) {}
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700452 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700453 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700454 return true;
455 }
456 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700457 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700458}
459
Lloyd Piquee83f9312018-02-01 12:53:17 -0800460class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700461public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700462 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000463 const char* name) :
464 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700465 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700466 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000467 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
468 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700469 mDispSync(dispSync),
470 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700471 mVsyncMutex(),
472 mPhaseOffset(phaseOffset),
473 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700474
Lloyd Piquee83f9312018-02-01 12:53:17 -0800475 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700476
Lloyd Piquee83f9312018-02-01 12:53:17 -0800477 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700478 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700479 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000480 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700481 static_cast<DispSync::Callback*>(this));
482 if (err != NO_ERROR) {
483 ALOGE("error registering vsync callback: %s (%d)",
484 strerror(-err), err);
485 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700486 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700487 } else {
488 status_t err = mDispSync->removeEventListener(
489 static_cast<DispSync::Callback*>(this));
490 if (err != NO_ERROR) {
491 ALOGE("error unregistering vsync callback: %s (%d)",
492 strerror(-err), err);
493 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700494 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700495 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700496 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700497 }
498
Lloyd Piquee83f9312018-02-01 12:53:17 -0800499 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700500 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700501 mCallback = callback;
502 }
503
Lloyd Piquee83f9312018-02-01 12:53:17 -0800504 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700505 Mutex::Autolock lock(mVsyncMutex);
506
507 // Normalize phaseOffset to [0, period)
508 auto period = mDispSync->getPeriod();
509 phaseOffset %= period;
510 if (phaseOffset < 0) {
511 // If we're here, then phaseOffset is in (-period, 0). After this
512 // operation, it will be in (0, period)
513 phaseOffset += period;
514 }
515 mPhaseOffset = phaseOffset;
516
517 // If we're not enabled, we don't need to mess with the listeners
518 if (!mEnabled) {
519 return;
520 }
521
522 // Remove the listener with the old offset
523 status_t err = mDispSync->removeEventListener(
524 static_cast<DispSync::Callback*>(this));
525 if (err != NO_ERROR) {
526 ALOGE("error unregistering vsync callback: %s (%d)",
527 strerror(-err), err);
528 }
529
530 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000531 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700532 static_cast<DispSync::Callback*>(this));
533 if (err != NO_ERROR) {
534 ALOGE("error registering vsync callback: %s (%d)",
535 strerror(-err), err);
536 }
537 }
538
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700539private:
540 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800541 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700542 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700543 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700544 callback = mCallback;
545
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700546 if (mTraceVsync) {
547 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700548 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700549 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700550 }
551
Peiyong Lin566a3b42018-01-09 18:22:43 -0800552 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700553 callback->onVSyncEvent(when);
554 }
555 }
556
Tim Murray4a4e4a22016-04-19 16:29:23 +0000557 const char* const mName;
558
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700559 int mValue;
560
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700561 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700562 const String8 mVsyncOnLabel;
563 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700564
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700565 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700566
567 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800568 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700569
570 Mutex mVsyncMutex; // Protects the following
571 nsecs_t mPhaseOffset;
572 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700573};
574
Lloyd Piquee83f9312018-02-01 12:53:17 -0800575class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700576public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800577 InjectVSyncSource() = default;
578 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700579
Lloyd Piquee83f9312018-02-01 12:53:17 -0800580 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700581 std::lock_guard<std::mutex> lock(mCallbackMutex);
582 mCallback = callback;
583 }
584
Lloyd Piquee83f9312018-02-01 12:53:17 -0800585 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700586 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700587 if (mCallback) {
588 mCallback->onVSyncEvent(when);
589 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700590 }
591
Lloyd Piquee83f9312018-02-01 12:53:17 -0800592 void setVSyncEnabled(bool) override {}
593 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700594
595private:
596 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800597 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700598};
599
Wei Wangf9b05ee2017-07-19 20:59:39 -0700600// Do not call property_set on main thread which will be blocked by init
601// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700602void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700603 ALOGI( "SurfaceFlinger's main thread ready to run. "
604 "Initializing graphics H/W...");
605
Thierry Strudel2924d012017-08-14 15:19:37 -0700606 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900607
Steven Thomasb02664d2017-07-26 18:48:28 -0700608 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800609
Steven Thomasb02664d2017-07-26 18:48:28 -0700610 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800611 mEventThreadSource =
612 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
613 true, "app");
614 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(), *this, false,
615 "appEventThread");
616 mSfEventThreadSource =
617 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
618 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800619
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800620 mSFEventThread = std::make_unique<impl::EventThread>(mSfEventThreadSource.get(), *this, true,
621 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800622 mEventQueue->setEventThread(mSFEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800623
Steven Thomasb02664d2017-07-26 18:48:28 -0700624 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800625 getBE().mRenderEngine =
626 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
627 hasWideColorDisplay
628 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
629 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800630 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700631
632 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
633 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800634 getBE().mHwc.reset(
635 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700636 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800637 // Process any initial hotplug and resulting display changes.
638 processDisplayHotplugEventsLocked();
639 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
640 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800641
Lloyd Piquefcd86612017-12-14 17:15:36 -0800642 // make the default display GLContext current so that we can create textures
643 // when creating Layers (which may happens before we render something)
644 getDefaultDisplayDeviceLocked()->makeCurrent();
645
Steven Thomas050b2c82017-03-06 11:45:16 -0800646 if (useVrFlinger) {
647 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700648 // This callback is called from the vr flinger dispatch thread. We
649 // need to call signalTransaction(), which requires holding
650 // mStateLock when we're not on the main thread. Acquiring
651 // mStateLock from the vr flinger dispatch thread might trigger a
652 // deadlock in surface flinger (see b/66916578), so post a message
653 // to be handled on the main thread instead.
654 sp<LambdaMessage> message = new LambdaMessage([=]() {
655 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
656 mVrFlingerRequestsDisplay = requestDisplay;
657 signalTransaction();
658 });
659 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800660 };
David Sodman105b7dc2017-11-04 20:28:14 -0700661 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
662 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800663 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800664 if (!mVrFlinger) {
665 ALOGE("Failed to start vrflinger");
666 }
667 }
668
Lloyd Pique379adc12018-01-22 17:31:47 -0800669 mEventControlThread = std::make_unique<impl::EventControlThread>(
670 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700671
Mathias Agopian92a979a2012-08-02 18:32:23 -0700672 // initialize our drawing state
673 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700674
Andy McFadden13a082e2012-08-24 10:16:42 -0700675 // set initial conditions (e.g. unblank default device)
676 initializeDisplays();
David Sodman4b7c4bc2017-11-17 12:13:59 -0800677 ALOGV("Displays initialized");
Andy McFadden13a082e2012-08-24 10:16:42 -0700678
David Sodmanbc815282017-11-05 18:57:52 -0800679 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700680
Wei Wangf9b05ee2017-07-19 20:59:39 -0700681 // Inform native graphics APIs whether the present timestamp is supported:
682 if (getHwComposer().hasCapability(
683 HWC2::Capability::PresentFenceIsNotReliable)) {
684 mStartPropertySetThread = new StartPropertySetThread(false);
685 } else {
686 mStartPropertySetThread = new StartPropertySetThread(true);
687 }
688
689 if (mStartPropertySetThread->Start() != NO_ERROR) {
690 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800691 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800692
Dan Stoza9e56aa02015-11-02 13:00:03 -0800693 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700694}
695
Romain Guy11d63f42017-07-20 12:47:14 -0700696void SurfaceFlinger::readPersistentProperties() {
697 char value[PROPERTY_VALUE_MAX];
698
699 property_get("persist.sys.sf.color_saturation", value, "1.0");
700 mSaturation = atof(value);
701 ALOGV("Saturation is set to %.2f", mSaturation);
Romain Guy54f154a2017-10-24 21:40:32 +0100702
703 property_get("persist.sys.sf.native_mode", value, "0");
704 mForceNativeColorMode = atoi(value) == 1;
705 if (mForceNativeColorMode) {
706 ALOGV("Forcing native color mode");
707 }
Romain Guy11d63f42017-07-20 12:47:14 -0700708}
709
Mathias Agopiana67e4182012-06-19 17:26:12 -0700710void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800711 // Start boot animation service by setting a property mailbox
712 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700713 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800714 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700715 if (mStartPropertySetThread->join() != NO_ERROR) {
716 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800717 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700718}
719
Mathias Agopian875d8e12013-06-07 15:35:48 -0700720size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800721 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700722}
723
Mathias Agopian875d8e12013-06-07 15:35:48 -0700724size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800725 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700726}
727
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800728// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800729
Jamie Gennis582270d2011-08-17 18:19:00 -0700730bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800731 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800732 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800733 return authenticateSurfaceTextureLocked(bufferProducer);
734}
735
736bool SurfaceFlinger::authenticateSurfaceTextureLocked(
737 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800738 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800739 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800740}
741
Brian Anderson6b376712017-04-04 10:51:39 -0700742status_t SurfaceFlinger::getSupportedFrameTimestamps(
743 std::vector<FrameEvent>* outSupported) const {
744 *outSupported = {
745 FrameEvent::REQUESTED_PRESENT,
746 FrameEvent::ACQUIRE,
747 FrameEvent::LATCH,
748 FrameEvent::FIRST_REFRESH_START,
749 FrameEvent::LAST_REFRESH_START,
750 FrameEvent::GPU_COMPOSITION_DONE,
751 FrameEvent::DEQUEUE_READY,
752 FrameEvent::RELEASE,
753 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700754 ConditionalLock _l(mStateLock,
755 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700756 if (!getHwComposer().hasCapability(
757 HWC2::Capability::PresentFenceIsNotReliable)) {
758 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
759 }
760 return NO_ERROR;
761}
762
Dan Stoza7f7da322014-05-02 15:26:25 -0700763status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
764 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800765 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700766 return BAD_VALUE;
767 }
768
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500769 if (!display.get())
770 return NAME_NOT_FOUND;
771
Jesse Hall692c7232012-11-08 15:41:56 -0800772 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700773 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800774 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700775 type = i;
776 break;
777 }
778 }
779
780 if (type < 0) {
781 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700782 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700783
Mathias Agopian8b736f12012-08-13 17:54:26 -0700784 // TODO: Not sure if display density should handled by SF any longer
785 class Density {
786 static int getDensityFromProperty(char const* propName) {
787 char property[PROPERTY_VALUE_MAX];
788 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800789 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700790 density = atoi(property);
791 }
792 return density;
793 }
794 public:
795 static int getEmuDensity() {
796 return getDensityFromProperty("qemu.sf.lcd_density"); }
797 static int getBuildDensity() {
798 return getDensityFromProperty("ro.sf.lcd_density"); }
799 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700800
Dan Stoza7f7da322014-05-02 15:26:25 -0700801 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700802
Steven Thomas6d8110b2017-08-31 18:24:21 -0700803 ConditionalLock _l(mStateLock,
804 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800805 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700806 DisplayInfo info = DisplayInfo();
807
Dan Stoza9e56aa02015-11-02 13:00:03 -0800808 float xdpi = hwConfig->getDpiX();
809 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700810
811 if (type == DisplayDevice::DISPLAY_PRIMARY) {
812 // The density of the device is provided by a build property
813 float density = Density::getBuildDensity() / 160.0f;
814 if (density == 0) {
815 // the build doesn't provide a density -- this is wrong!
816 // use xdpi instead
817 ALOGE("ro.sf.lcd_density must be defined as a build property");
818 density = xdpi / 160.0f;
819 }
820 if (Density::getEmuDensity()) {
821 // if "qemu.sf.lcd_density" is specified, it overrides everything
822 xdpi = ydpi = density = Density::getEmuDensity();
823 density /= 160.0f;
824 }
825 info.density = density;
826
827 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700828 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800829 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700830 } else {
831 // TODO: where should this value come from?
832 static const int TV_DENSITY = 213;
833 info.density = TV_DENSITY / 160.0f;
834 info.orientation = 0;
835 }
836
Dan Stoza9e56aa02015-11-02 13:00:03 -0800837 info.w = hwConfig->getWidth();
838 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700839 info.xdpi = xdpi;
840 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800841 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900842 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800843
Andy McFadden91b2ca82014-06-13 14:04:23 -0700844 // This is how far in advance a buffer must be queued for
845 // presentation at a given time. If you want a buffer to appear
846 // on the screen at time N, you must submit the buffer before
847 // (N - presentationDeadline).
848 //
849 // Normally it's one full refresh period (to give SF a chance to
850 // latch the buffer), but this can be reduced by configuring a
851 // DispSync offset. Any additional delays introduced by the hardware
852 // composer or panel must be accounted for here.
853 //
854 // We add an additional 1ms to allow for processing time and
855 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800856 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800857 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700858
859 // All non-virtual displays are currently considered secure.
860 info.secure = true;
861
Michael Wright28f24d02016-07-12 13:30:53 -0700862 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700863 }
864
Dan Stoza7f7da322014-05-02 15:26:25 -0700865 return NO_ERROR;
866}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700867
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800868status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700869 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800870 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700871 return BAD_VALUE;
872 }
873
874 // FIXME for now we always return stats for the primary display
875 memset(stats, 0, sizeof(*stats));
876 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
877 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
878 return NO_ERROR;
879}
880
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700881int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800882 if (display == nullptr) {
883 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800884 return BAD_VALUE;
885 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700886
887 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800888 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700889 return device->getActiveConfig();
890 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700891
Dan Stoza24a42e92015-03-09 10:04:11 -0700892 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700893}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700894
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700895void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
896 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
897 this);
898 int32_t type = hw->getDisplayType();
899 int currentMode = hw->getActiveConfig();
900
901 if (mode == currentMode) {
902 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
903 return;
904 }
905
906 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
907 ALOGW("Trying to set config for virtual display");
908 return;
909 }
910
911 hw->setActiveConfig(mode);
912 getHwComposer().setActiveConfig(type, mode);
913}
914
915status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
916 class MessageSetActiveConfig: public MessageBase {
917 SurfaceFlinger& mFlinger;
918 sp<IBinder> mDisplay;
919 int mMode;
920 public:
921 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
922 int mode) :
923 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
924 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700925 Vector<DisplayInfo> configs;
926 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700927 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700928 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700929 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700930 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700931 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700932 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800933 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700934 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700935 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700936 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
937 ALOGW("Attempt to set active config = %d for virtual display",
938 mMode);
939 } else {
940 mFlinger.setActiveConfigInternal(hw, mMode);
941 }
942 return true;
943 }
944 };
945 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
946 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700947 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700948}
Michael Wright28f24d02016-07-12 13:30:53 -0700949status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -0700950 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700951 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
952 return BAD_VALUE;
953 }
954
955 if (!display.get()) {
956 return NAME_NOT_FOUND;
957 }
958
959 int32_t type = NAME_NOT_FOUND;
960 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
961 if (display == mBuiltinDisplays[i]) {
962 type = i;
963 break;
964 }
965 }
966
967 if (type < 0) {
968 return type;
969 }
970
Peiyong Lina52f0292018-03-14 17:26:31 -0700971 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700972 {
973 ConditionalLock _l(mStateLock,
974 std::this_thread::get_id() != mMainThreadId);
975 modes = getHwComposer().getColorModes(type);
976 }
Michael Wright28f24d02016-07-12 13:30:53 -0700977 outColorModes->clear();
978 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
979
980 return NO_ERROR;
981}
982
Peiyong Lina52f0292018-03-14 17:26:31 -0700983ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700984 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700985 if (device != nullptr) {
986 return device->getActiveColorMode();
987 }
Peiyong Lina52f0292018-03-14 17:26:31 -0700988 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -0700989}
990
991void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lina52f0292018-03-14 17:26:31 -0700992 ColorMode mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700993 int32_t type = hw->getDisplayType();
Peiyong Lina52f0292018-03-14 17:26:31 -0700994 ColorMode currentMode = hw->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -0700995
996 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700997 return;
998 }
999
1000 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1001 ALOGW("Trying to set config for virtual display");
1002 return;
1003 }
1004
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001005 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
1006 hw->getDisplayType());
1007
Michael Wright28f24d02016-07-12 13:30:53 -07001008 hw->setActiveColorMode(mode);
1009 getHwComposer().setActiveColorMode(type, mode);
1010}
1011
1012
1013status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001014 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -07001015 class MessageSetActiveColorMode: public MessageBase {
1016 SurfaceFlinger& mFlinger;
1017 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -07001018 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001019 public:
1020 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -07001021 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -07001022 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1023 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -07001024 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001025 mFlinger.getDisplayColorModes(mDisplay, &modes);
1026 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -07001027 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001028 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1029 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001030 return true;
1031 }
1032 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1033 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001034 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1035 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001036 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001037 ALOGW("Attempt to set active color mode %s %d for virtual display",
1038 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001039 } else {
1040 mFlinger.setActiveColorModeInternal(hw, mMode);
1041 }
1042 return true;
1043 }
1044 };
1045 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1046 postMessageSync(msg);
1047 return NO_ERROR;
1048}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001049
Svetoslavd85084b2014-03-20 10:28:31 -07001050status_t SurfaceFlinger::clearAnimationFrameStats() {
1051 Mutex::Autolock _l(mStateLock);
1052 mAnimFrameTracker.clearStats();
1053 return NO_ERROR;
1054}
1055
1056status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1057 Mutex::Autolock _l(mStateLock);
1058 mAnimFrameTracker.getStats(outStats);
1059 return NO_ERROR;
1060}
1061
Dan Stozac4f471e2016-03-24 09:31:08 -07001062status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1063 HdrCapabilities* outCapabilities) const {
1064 Mutex::Autolock _l(mStateLock);
1065
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001066 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001067 if (displayDevice == nullptr) {
1068 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1069 return BAD_VALUE;
1070 }
1071
1072 std::unique_ptr<HdrCapabilities> capabilities =
David Sodman105b7dc2017-11-04 20:28:14 -07001073 getBE().mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
Dan Stozac4f471e2016-03-24 09:31:08 -07001074 if (capabilities) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001075 if (displayDevice->getWideColorSupport() && !displayDevice->getHdrSupport()) {
1076 // insert HDR10 as we will force client composition for HDR10
1077 // layers
1078 std::vector<int32_t> types = capabilities->getSupportedHdrTypes();
1079 types.push_back(HAL_HDR_HDR10);
1080
1081 *outCapabilities = HdrCapabilities(types,
1082 capabilities->getDesiredMaxLuminance(),
1083 capabilities->getDesiredMaxAverageLuminance(),
1084 capabilities->getDesiredMinLuminance());
1085 } else {
1086 *outCapabilities = std::move(*capabilities);
1087 }
Dan Stozac4f471e2016-03-24 09:31:08 -07001088 } else {
1089 return BAD_VALUE;
1090 }
1091
1092 return NO_ERROR;
1093}
1094
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001095status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001096 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1097 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001098
Chia-I Wu90f669f2017-10-05 14:24:41 -07001099 if (mInjectVSyncs == enable) {
1100 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001101 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001102
1103 if (enable) {
1104 ALOGV("VSync Injections enabled");
1105 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001106 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique0fcde1b2017-12-20 16:50:21 -08001107 mInjectorEventThread =
1108 std::make_unique<impl::EventThread>(mVSyncInjector.get(), *this, false,
1109 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001110 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001111 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001112 } else {
1113 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001114 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001115 }
1116
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001117 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001118 });
1119 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001120 return NO_ERROR;
1121}
1122
1123status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001124 Mutex::Autolock _l(mStateLock);
1125
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001126 if (!mInjectVSyncs) {
1127 ALOGE("VSync Injections not enabled");
1128 return BAD_VALUE;
1129 }
1130 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1131 ALOGV("Injecting VSync inside SurfaceFlinger");
1132 mVSyncInjector->onInjectSyncEvent(when);
1133 }
1134 return NO_ERROR;
1135}
1136
Lloyd Pique755e3192018-01-31 16:46:15 -08001137status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1138 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001139 IPCThreadState* ipc = IPCThreadState::self();
1140 const int pid = ipc->getCallingPid();
1141 const int uid = ipc->getCallingUid();
1142 if ((uid != AID_SHELL) &&
1143 !PermissionCache::checkPermission(sDump, pid, uid)) {
1144 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1145 return PERMISSION_DENIED;
1146 }
1147
1148 // Try to acquire a lock for 1s, fail gracefully
1149 const status_t err = mStateLock.timedLock(s2ns(1));
1150 const bool locked = (err == NO_ERROR);
1151 if (!locked) {
1152 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1153 return TIMED_OUT;
1154 }
1155
1156 outLayers->clear();
1157 mCurrentState.traverseInZOrder([&](Layer* layer) {
1158 outLayers->push_back(layer->getLayerDebugInfo());
1159 });
1160
1161 mStateLock.unlock();
1162 return NO_ERROR;
1163}
1164
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001165// ----------------------------------------------------------------------------
1166
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001167sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1168 ISurfaceComposer::VsyncSource vsyncSource) {
1169 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1170 return mSFEventThread->createEventConnection();
1171 } else {
1172 return mEventThread->createEventConnection();
1173 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001174}
1175
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001176// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001177
1178void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001179 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001180}
1181
1182void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001183 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001184}
1185
1186void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001187 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001188}
1189
1190void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001191 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001192 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001193}
1194
1195status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001196 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001197 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001198}
1199
1200status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001201 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001202 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001203 if (res == NO_ERROR) {
1204 msg->wait();
1205 }
1206 return res;
1207}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001208
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001209void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001210 do {
1211 waitForEvent();
1212 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001213}
1214
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001215void SurfaceFlinger::enableHardwareVsync() {
1216 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001217 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001218 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001219 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1220 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001221 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001222 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001223}
1224
Jesse Hall948fe0c2013-10-14 12:56:09 -07001225void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001226 Mutex::Autolock _l(mHWVsyncLock);
1227
Jesse Hall948fe0c2013-10-14 12:56:09 -07001228 if (makeAvailable) {
1229 mHWVsyncAvailable = true;
1230 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001231 // Hardware vsync is not currently available, so abort the resync
1232 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001233 return;
1234 }
1235
David Sodman105b7dc2017-11-04 20:28:14 -07001236 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001237 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001238
1239 mPrimaryDispSync.reset();
1240 mPrimaryDispSync.setPeriod(period);
1241
1242 if (!mPrimaryHWVsyncEnabled) {
1243 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001244 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1245 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001246 mPrimaryHWVsyncEnabled = true;
1247 }
1248}
1249
Jesse Hall948fe0c2013-10-14 12:56:09 -07001250void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001251 Mutex::Autolock _l(mHWVsyncLock);
1252 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001253 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1254 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001255 mPrimaryDispSync.endResync();
1256 mPrimaryHWVsyncEnabled = false;
1257 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001258 if (makeUnavailable) {
1259 mHWVsyncAvailable = false;
1260 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001261}
1262
Tim Murray4a4e4a22016-04-19 16:29:23 +00001263void SurfaceFlinger::resyncWithRateLimit() {
1264 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001265
1266 // No explicit locking is needed here since EventThread holds a lock while calling this method
1267 static nsecs_t sLastResyncAttempted = 0;
1268 const nsecs_t now = systemTime();
1269 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001270 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001271 }
Dan Stoza57164302017-05-08 14:03:54 -07001272 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001273}
1274
Steven Thomasb02664d2017-07-26 18:48:28 -07001275void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1276 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001277 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001278 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001279 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001280 return;
1281 }
1282
1283 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001284 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001285 return;
1286 }
1287
Jamie Gennisd1700752013-10-14 12:22:52 -07001288 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001289
Jamie Gennisd1700752013-10-14 12:22:52 -07001290 { // Scope for the lock
1291 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001292 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001293 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001294 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001295 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001296
1297 if (needsHwVsync) {
1298 enableHardwareVsync();
1299 } else {
1300 disableHardwareVsync(false);
1301 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001302}
1303
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001304void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001305 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1306 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001307}
1308
Lloyd Pique715a2c12017-12-14 17:18:08 -08001309void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1310 HWC2::Connection connection) {
1311 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1312 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001313
Lloyd Piqueba04e622017-12-14 17:11:26 -08001314 // Ignore events that do not have the right sequenceId.
1315 if (sequenceId != getBE().mComposerSequenceId) {
1316 return;
1317 }
1318
Steven Thomasb02664d2017-07-26 18:48:28 -07001319 // Only lock if we're not on the main thread. This function is normally
1320 // called on a hwbinder thread, but for the primary display it's called on
1321 // the main thread with the state lock already held, so don't attempt to
1322 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001323 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001324
Lloyd Pique715a2c12017-12-14 17:18:08 -08001325 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001326
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001327 if (std::this_thread::get_id() == mMainThreadId) {
1328 // Process all pending hot plug events immediately if we are on the main thread.
1329 processDisplayHotplugEventsLocked();
1330 }
1331
Lloyd Piqueba04e622017-12-14 17:11:26 -08001332 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001333}
1334
Steven Thomasb02664d2017-07-26 18:48:28 -07001335void SurfaceFlinger::onRefreshReceived(int sequenceId,
1336 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001337 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001338 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001339 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001340 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001341 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001342}
1343
Dan Stoza9e56aa02015-11-02 13:00:03 -08001344void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001345 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001346 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001347 getHwComposer().setVsyncEnabled(disp,
1348 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001349}
1350
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001351// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001352void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001353 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001354 // Clear the drawing state so that the logic inside of
1355 // handleTransactionLocked will fire. It will determine the delta between
1356 // mCurrentState and mDrawingState and re-apply all changes when we make the
1357 // transition.
1358 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001359 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001360 mDisplays.clear();
1361}
1362
Steven Thomas050b2c82017-03-06 11:45:16 -08001363void SurfaceFlinger::updateVrFlinger() {
1364 if (!mVrFlinger)
1365 return;
1366 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001367 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001368 return;
1369 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001370
David Sodman105b7dc2017-11-04 20:28:14 -07001371 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001372 ALOGE("Vr flinger is only supported for remote hardware composer"
1373 " service connections. Ignoring request to transition to vr"
1374 " flinger.");
1375 mVrFlingerRequestsDisplay = false;
1376 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001377 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001378
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001379 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001380
Steven Thomasb02664d2017-07-26 18:48:28 -07001381 int currentDisplayPowerMode = getDisplayDeviceLocked(
1382 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001383
Steven Thomasb02664d2017-07-26 18:48:28 -07001384 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001385 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001386 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001387
Steven Thomasb02664d2017-07-26 18:48:28 -07001388 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001389 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001390 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1391 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001392 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001393
David Sodman105b7dc2017-11-04 20:28:14 -07001394 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1395 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001396
1397 if (vrFlingerRequestsDisplay) {
1398 mVrFlinger->GrantDisplayOwnership();
1399 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001400 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001401 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001402
1403 mVisibleRegionsDirty = true;
1404 invalidateHwcGeometry();
1405
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001406 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001407 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1408 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1409 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001410
Steven Thomasb02664d2017-07-26 18:48:28 -07001411 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001412 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001413 const nsecs_t period = activeConfig->getVsyncPeriod();
1414 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001415
Steven Thomasb02664d2017-07-26 18:48:28 -07001416 // Use phase of 0 since phase is not known.
1417 // Use latency of 0, which will snap to the ideal latency.
1418 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001419
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001420 android_atomic_or(1, &mRepaintEverything);
1421 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001422}
1423
Mathias Agopian4fec8732012-06-29 14:12:52 -07001424void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001425 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001426 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001427 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001428 bool frameMissed = !mHadClientComposition &&
1429 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001430 (mPreviousPresentFence->getSignalTime() ==
1431 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001432 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001433 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001434 signalLayerUpdate();
1435 break;
1436 }
1437
Steven Thomas050b2c82017-03-06 11:45:16 -08001438 // Now that we're going to make it to the handleMessageTransaction()
1439 // call below it's safe to call updateVrFlinger(), which will
1440 // potentially trigger a display handoff.
1441 updateVrFlinger();
1442
Dan Stoza6b9454d2014-11-07 16:00:59 -08001443 bool refreshNeeded = handleMessageTransaction();
1444 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001445 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001446 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001447 // Signal a refresh if a transaction modified the window state,
1448 // a new buffer was latched, or if HWC has requested a full
1449 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001450 signalRefresh();
1451 }
1452 break;
1453 }
1454 case MessageQueue::REFRESH: {
1455 handleMessageRefresh();
1456 break;
1457 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001458 }
1459}
1460
Dan Stoza6b9454d2014-11-07 16:00:59 -08001461bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001462 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001463 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001464 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001465 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001466 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001467 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001468}
1469
Dan Stoza6b9454d2014-11-07 16:00:59 -08001470bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001471 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001472 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001473}
1474
1475void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001476 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001477
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001478 mRefreshPending = false;
1479
Pablo Ceballos40845df2016-01-25 17:41:15 -08001480 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001481
Brian Andersond6927fb2016-07-23 23:37:30 -07001482 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001483 rebuildLayerStacks();
1484 setUpHWComposer();
1485 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001486 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001487 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001488 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001489 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001490
David Sodman105b7dc2017-11-04 20:28:14 -07001491 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001492
1493 mHadClientComposition = false;
1494 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1495 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1496 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001497 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001498 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001499
Dan Stoza9e56aa02015-11-02 13:00:03 -08001500 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001501}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001502
Mathias Agopiancd60f992012-08-16 16:28:27 -07001503void SurfaceFlinger::doDebugFlashRegions()
1504{
1505 // is debugging enabled
1506 if (CC_LIKELY(!mDebugRegion))
1507 return;
1508
1509 const bool repaintEverything = mRepaintEverything;
1510 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1511 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001512 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001513 // transform the dirty region into this screen's coordinate space
1514 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1515 if (!dirtyRegion.isEmpty()) {
1516 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001517 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001518
1519 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001520 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001521 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001522 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1523
Mathias Agopianda27af92012-09-13 18:17:13 -07001524 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001525 }
1526 }
1527 }
1528
1529 postFramebuffer();
1530
1531 if (mDebugRegion > 1) {
1532 usleep(mDebugRegion * 1000);
1533 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001534
Dan Stoza9e56aa02015-11-02 13:00:03 -08001535 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001536 auto& displayDevice = mDisplays[displayId];
1537 if (!displayDevice->isDisplayOn()) {
1538 continue;
1539 }
1540
David Sodman105b7dc2017-11-04 20:28:14 -07001541 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1542 ALOGE_IF(result != NO_ERROR,
1543 "prepareFrame for display %zd failed:"
1544 " %d (%s)",
1545 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001546 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001547}
1548
Adrian Roos1e1a1282017-11-01 19:05:31 +01001549void SurfaceFlinger::doTracing(const char* where) {
1550 ATRACE_CALL();
1551 ATRACE_NAME(where);
1552 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001553 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001554 }
1555}
1556
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001557void SurfaceFlinger::logLayerStats() {
1558 ATRACE_CALL();
1559 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1560 int32_t hwcId = -1;
1561 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1562 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1563 if (displayDevice->isPrimary()) {
1564 hwcId = displayDevice->getHwcDisplayId();
1565 break;
1566 }
1567 }
1568 if (hwcId < 0) {
1569 ALOGE("LayerStats: Hmmm, no primary display?");
1570 return;
1571 }
1572 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1573 }
1574}
1575
Brian Andersond6927fb2016-07-23 23:37:30 -07001576void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001577{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001578 ATRACE_CALL();
1579 ALOGV("preComposition");
1580
Mathias Agopiancd60f992012-08-16 16:28:27 -07001581 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001582 mDrawingState.traverseInZOrder([&](Layer* layer) {
1583 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001584 needExtraInvalidate = true;
1585 }
Robert Carr2047fae2016-11-28 14:09:09 -08001586 });
1587
Mathias Agopiancd60f992012-08-16 16:28:27 -07001588 if (needExtraInvalidate) {
1589 signalLayerUpdate();
1590 }
1591}
1592
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001593void SurfaceFlinger::updateCompositorTiming(
1594 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1595 std::shared_ptr<FenceTime>& presentFenceTime) {
1596 // Update queue of past composite+present times and determine the
1597 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001598 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001599 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001600 while (!getBE().mCompositePresentTimes.empty()) {
1601 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001602 // Cached values should have been updated before calling this method,
1603 // which helps avoid duplicate syscalls.
1604 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1605 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1606 break;
1607 }
1608 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001609 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001610 }
1611
1612 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001613 while (getBE().mCompositePresentTimes.size() > 16) {
1614 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001615 }
1616
Brian Andersond0010582017-03-07 13:20:31 -08001617 setCompositorTimingSnapped(
1618 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1619}
1620
1621void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1622 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001623 // Integer division and modulo round toward 0 not -inf, so we need to
1624 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001625 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001626 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1627 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1628
Brian Andersond0010582017-03-07 13:20:31 -08001629 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1630 if (idealLatency <= 0) {
1631 idealLatency = vsyncInterval;
1632 }
1633
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001634 // Snap the latency to a value that removes scheduling jitter from the
1635 // composition and present times, which often have >1ms of jitter.
1636 // Reducing jitter is important if an app attempts to extrapolate
1637 // something (such as user input) to an accurate diasplay time.
1638 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1639 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001640 nsecs_t bias = vsyncInterval / 2;
1641 int64_t extraVsyncs =
1642 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1643 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1644 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001645
David Sodman99974d22017-11-28 12:04:33 -08001646 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1647 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1648 getBE().mCompositorTiming.interval = vsyncInterval;
1649 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001650}
1651
1652void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001653{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001654 ATRACE_CALL();
1655 ALOGV("postComposition");
1656
Brian Anderson3546a3f2016-07-14 11:51:14 -07001657 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001658 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001659 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001660 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001661 }
1662
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001663 // |mStateLock| not needed as we are on the main thread
1664 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001665
David Sodman73beded2017-11-15 11:56:06 -08001666 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001667 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001668 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001669 glCompositionDoneFenceTime =
1670 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001671 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001672 } else {
1673 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1674 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001675
David Sodman73beded2017-11-15 11:56:06 -08001676 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001677 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001678 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001679 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001680
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001681 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1682 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1683
1684 // We use the refreshStartTime which might be sampled a little later than
1685 // when we started doing work for this frame, but that should be okay
1686 // since updateCompositorTiming has snapping logic.
1687 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001688 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001689 CompositorTiming compositorTiming;
1690 {
David Sodman99974d22017-11-28 12:04:33 -08001691 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1692 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001693 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001694
Robert Carr2047fae2016-11-28 14:09:09 -08001695 mDrawingState.traverseInZOrder([&](Layer* layer) {
1696 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001697 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001698 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001699 recordBufferingStats(layer->getName().string(),
1700 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001701 }
Robert Carr2047fae2016-11-28 14:09:09 -08001702 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001703
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001704 if (presentFenceTime->isValid()) {
1705 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001706 enableHardwareVsync();
1707 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001708 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001709 }
1710 }
1711
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001712 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001713 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001714 enableHardwareVsync();
1715 }
1716 }
1717
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001718 if (mAnimCompositionPending) {
1719 mAnimCompositionPending = false;
1720
Brian Anderson4e606e32017-03-16 15:34:57 -07001721 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001722 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001723 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001724 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001725 // The HWC doesn't support present fences, so use the refresh
1726 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001727 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001728 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001729 mAnimFrameTracker.setActualPresentTime(presentTime);
1730 }
1731 mAnimFrameTracker.advanceFrame();
1732 }
Dan Stozab90cf072015-03-05 11:05:59 -08001733
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001734 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1735 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001736 return;
1737 }
1738
1739 nsecs_t currentTime = systemTime();
1740 if (mHasPoweredOff) {
1741 mHasPoweredOff = false;
1742 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001743 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001744 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001745 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1746 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001747 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001748 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001749 }
David Sodman4a36e932017-11-07 14:29:47 -08001750 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001751 }
David Sodman4a36e932017-11-07 14:29:47 -08001752 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001753}
1754
1755void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001756 ATRACE_CALL();
1757 ALOGV("rebuildLayerStacks");
1758
Mathias Agopiancd60f992012-08-16 16:28:27 -07001759 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001760 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001761 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001762 mVisibleRegionsDirty = false;
1763 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001764
Jeff Sharkey76488112017-02-27 14:15:18 -07001765 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1766 Region opaqueRegion;
1767 Region dirtyRegion;
1768 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001769 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001770 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1771 const Transform& tr(displayDevice->getTransform());
1772 const Rect bounds(displayDevice->getBounds());
1773 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001774 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001775
Jeff Sharkey76488112017-02-27 14:15:18 -07001776 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001777 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001778 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1779 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001780 Region drawRegion(tr.transform(
1781 layer->visibleNonTransparentRegion));
1782 drawRegion.andSelf(bounds);
1783 if (!drawRegion.isEmpty()) {
1784 layersSortedByZ.add(layer);
1785 } else {
1786 // Clear out the HWC layer if this layer was
1787 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001788 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001789 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001790 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001791 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001792 // WM changes displayDevice->layerStack upon sleep/awake.
1793 // Here we make sure we delete the HWC layers even if
1794 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001795 hwcLayerDestroyed = layer->destroyHwcLayer(
1796 displayDevice->getHwcDisplayId());
1797 }
1798
1799 // If a layer is not going to get a release fence because
1800 // it is invisible, but it is also going to release its
1801 // old buffer, add it to the list of layers needing
1802 // fences.
1803 if (hwcLayerDestroyed) {
1804 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1805 mLayersWithQueuedFrames.cend(), layer);
1806 if (found != mLayersWithQueuedFrames.cend()) {
1807 layersNeedingFences.add(layer);
1808 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001809 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001810 });
1811 }
1812 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001813 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001814 displayDevice->undefinedRegion.set(bounds);
1815 displayDevice->undefinedRegion.subtractSelf(
1816 tr.transform(opaqueRegion));
1817 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001818 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001819 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001820}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001821
Romain Guy0147a172017-06-01 13:53:56 -07001822mat4 SurfaceFlinger::computeSaturationMatrix() const {
1823 if (mSaturation == 1.0f) {
1824 return mat4();
1825 }
1826
1827 // Rec.709 luma coefficients
1828 float3 luminance{0.213f, 0.715f, 0.072f};
1829 luminance *= 1.0f - mSaturation;
1830 return mat4(
1831 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1832 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1833 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1834 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1835 );
1836}
1837
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001838// pickColorMode translates a given dataspace into the best available color mode.
1839// Currently only support sRGB and Display-P3.
Peiyong Lina52f0292018-03-14 17:26:31 -07001840ColorMode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Romain Guy54f154a2017-10-24 21:40:32 +01001841 if (mForceNativeColorMode) {
Peiyong Lina52f0292018-03-14 17:26:31 -07001842 return ColorMode::NATIVE;
Romain Guy54f154a2017-10-24 21:40:32 +01001843 }
1844
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001845 switch (dataSpace) {
1846 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1847 // system expects.
1848 case HAL_DATASPACE_UNKNOWN:
1849 case HAL_DATASPACE_SRGB:
1850 case HAL_DATASPACE_V0_SRGB:
Peiyong Lina52f0292018-03-14 17:26:31 -07001851 return ColorMode::SRGB;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001852 break;
1853
1854 case HAL_DATASPACE_DISPLAY_P3:
Peiyong Lina52f0292018-03-14 17:26:31 -07001855 return ColorMode::DISPLAY_P3;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001856 break;
1857
1858 default:
1859 // TODO (courtneygo): Do we want to assert an error here?
1860 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1861 dataSpace);
Peiyong Lina52f0292018-03-14 17:26:31 -07001862 return ColorMode::SRGB;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001863 break;
1864 }
1865}
1866
Romain Guy0147a172017-06-01 13:53:56 -07001867android_dataspace SurfaceFlinger::bestTargetDataSpace(
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001868 android_dataspace a, android_dataspace b, bool hasHdr) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001869 // Only support sRGB and Display-P3 right now.
1870 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1871 return HAL_DATASPACE_DISPLAY_P3;
1872 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001873 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1874 return HAL_DATASPACE_DISPLAY_P3;
1875 }
1876 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1877 return HAL_DATASPACE_DISPLAY_P3;
1878 }
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001879 if (!hasHdr) {
1880 if (a == HAL_DATASPACE_BT2020_PQ || b == HAL_DATASPACE_BT2020_PQ) {
1881 return HAL_DATASPACE_DISPLAY_P3;
1882 }
1883 if (a == HAL_DATASPACE_BT2020_ITU_PQ || b == HAL_DATASPACE_BT2020_ITU_PQ) {
1884 return HAL_DATASPACE_DISPLAY_P3;
1885 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001886 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001887
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001888 return HAL_DATASPACE_V0_SRGB;
1889}
1890
Mathias Agopiancd60f992012-08-16 16:28:27 -07001891void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001892 ATRACE_CALL();
1893 ALOGV("setUpHWComposer");
1894
Jesse Hall028dc8f2013-08-20 16:35:32 -07001895 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001896 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1897 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1898 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1899
1900 // If nothing has changed (!dirty), don't recompose.
1901 // If something changed, but we don't currently have any visible layers,
1902 // and didn't when we last did a composition, then skip it this time.
1903 // The second rule does two things:
1904 // - When all layers are removed from a display, we'll emit one black
1905 // frame, then nothing more until we get new layers.
1906 // - When a display is created with a private layer stack, we won't
1907 // emit any black frames until a layer is added to the layer stack.
1908 bool mustRecompose = dirty && !(empty && wasEmpty);
1909
1910 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1911 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1912 mustRecompose ? "doing" : "skipping",
1913 dirty ? "+" : "-",
1914 empty ? "+" : "-",
1915 wasEmpty ? "+" : "-");
1916
Dan Stoza71433162014-02-04 16:22:36 -08001917 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001918
1919 if (mustRecompose) {
1920 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1921 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001922 }
1923
Dan Stoza9e56aa02015-11-02 13:00:03 -08001924 // build the h/w work list
1925 if (CC_UNLIKELY(mGeometryInvalid)) {
1926 mGeometryInvalid = false;
1927 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1928 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1929 const auto hwcId = displayDevice->getHwcDisplayId();
1930 if (hwcId >= 0) {
1931 const Vector<sp<Layer>>& currentLayers(
1932 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001933 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001934 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001935 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07001936 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001937 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001938 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001939 }
1940 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001941
Robert Carrae060832016-11-28 10:51:00 -08001942 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001943 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001944 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001945 }
1946 }
1947 }
1948 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001949 }
Riley Andrews03414a12014-07-01 14:22:59 -07001950
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001951
Romain Guy0147a172017-06-01 13:53:56 -07001952 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001953
Dan Stoza9e56aa02015-11-02 13:00:03 -08001954 // Set the per-frame data
1955 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1956 auto& displayDevice = mDisplays[displayId];
1957 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001958
Dan Stoza9e56aa02015-11-02 13:00:03 -08001959 if (hwcId < 0) {
1960 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001961 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001962 if (colorMatrix != mPreviousColorMatrix) {
David Sodman105b7dc2017-11-04 20:28:14 -07001963 status_t result = getBE().mHwc->setColorTransform(hwcId, colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001964 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1965 "display %zd: %d", displayId, result);
1966 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001967 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001968 if ((layer->getDataSpace() == HAL_DATASPACE_BT2020_PQ ||
1969 layer->getDataSpace() == HAL_DATASPACE_BT2020_ITU_PQ) &&
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001970 !displayDevice->getHdrSupport()) {
1971 layer->forceClientComposition(hwcId);
1972 }
1973
chaviwc9232ed2017-11-14 15:31:15 -08001974 if (layer->getForceClientComposition(hwcId)) {
1975 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1976 layer->setCompositionType(hwcId, HWC2::Composition::Client);
1977 continue;
1978 }
1979
Dan Stoza9e56aa02015-11-02 13:00:03 -08001980 layer->setPerFrameData(displayDevice);
1981 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001982
1983 if (hasWideColorDisplay) {
Peiyong Lina52f0292018-03-14 17:26:31 -07001984 ColorMode newColorMode;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001985 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1986
1987 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001988 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace,
1989 displayDevice->getHdrSupport());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001990 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1991 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1992 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1993 }
1994 newColorMode = pickColorMode(newDataSpace);
1995
Thierry Strudel2924d012017-08-14 15:19:37 -07001996 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001997 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001998 }
1999
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002000 mPreviousColorMatrix = colorMatrix;
2001
David Sodman4b7c4bc2017-11-17 12:13:59 -08002002 for (size_t dpy = 0; dpy < mDisplays.size(); dpy++) {
2003 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
2004 const auto hwcId = displayDevice->getHwcDisplayId();
2005 if (hwcId >= 0) {
2006 const Vector<sp<Layer>>& currentLayers(
2007 displayDevice->getVisibleLayersSortedByZ());
2008 for (auto& layer : currentLayers) {
2009 layer->configureHwcLayer(displayDevice);
2010 }
2011 }
2012 }
2013
Dan Stoza9e56aa02015-11-02 13:00:03 -08002014 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002015 auto& displayDevice = mDisplays[displayId];
2016 if (!displayDevice->isDisplayOn()) {
2017 continue;
2018 }
2019
David Sodman105b7dc2017-11-04 20:28:14 -07002020 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002021 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2022 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002023 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002024}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002025
Mathias Agopiancd60f992012-08-16 16:28:27 -07002026void SurfaceFlinger::doComposition() {
2027 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002028 ALOGV("doComposition");
2029
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002030 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002031 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002032 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002033 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002034 // transform the dirty region into this screen's coordinate space
2035 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002036
2037 // repaint the framebuffer (if needed)
2038 doDisplayComposition(hw, dirtyRegion);
2039
Mathias Agopiancd60f992012-08-16 16:28:27 -07002040 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002041 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002042 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002043 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002044 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002045}
2046
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002047void SurfaceFlinger::postFramebuffer()
2048{
Mathias Agopian841cde52012-03-01 15:44:37 -08002049 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002050 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002051
Mathias Agopiana44b0412011-10-16 18:46:35 -07002052 const nsecs_t now = systemTime();
2053 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002054
Dan Stoza9e56aa02015-11-02 13:00:03 -08002055 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2056 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002057 if (!displayDevice->isDisplayOn()) {
2058 continue;
2059 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002060 const auto hwcId = displayDevice->getHwcDisplayId();
2061 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002062 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002063 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002064 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002065 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002066 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002067 // The layer buffer from the previous frame (if any) is released
2068 // by HWC only when the release fence from this frame (if any) is
2069 // signaled. Always get the release fence from HWC first.
2070 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002071 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002072
2073 // If the layer was client composited in the previous frame, we
2074 // need to merge with the previous client target acquire fence.
2075 // Since we do not track that, always merge with the current
2076 // client target acquire fence when it is available, even though
2077 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002078 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002079 releaseFence = Fence::merge("LayerRelease", releaseFence,
2080 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002081 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002082
David Sodmanb8af7922017-12-21 15:17:55 -08002083 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002084 }
Chia-I Wu83806892017-11-16 10:50:20 -08002085
2086 // We've got a list of layers needing fences, that are disjoint with
2087 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2088 // supply them with the present fence.
2089 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002090 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002091 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002092 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002093 }
2094 }
2095
Dan Stoza9e56aa02015-11-02 13:00:03 -08002096 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002097 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002098 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002099 }
2100
Mathias Agopiana44b0412011-10-16 18:46:35 -07002101 mLastSwapBufferTime = systemTime() - now;
2102 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002103
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002104 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002105 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2106 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2107 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2108 logFrameStats();
2109 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002110 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002111}
2112
Mathias Agopian87baae12012-07-31 12:38:26 -07002113void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002114{
Mathias Agopian841cde52012-03-01 15:44:37 -08002115 ATRACE_CALL();
2116
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002117 // here we keep a copy of the drawing state (that is the state that's
2118 // going to be overwritten by handleTransactionLocked()) outside of
2119 // mStateLock so that the side-effects of the State assignment
2120 // don't happen with mStateLock held (which can cause deadlocks).
2121 State drawingState(mDrawingState);
2122
Mathias Agopianca4d3602011-05-19 15:38:14 -07002123 Mutex::Autolock _l(mStateLock);
2124 const nsecs_t now = systemTime();
2125 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002126
Mathias Agopianca4d3602011-05-19 15:38:14 -07002127 // Here we're guaranteed that some transaction flags are set
2128 // so we can call handleTransactionLocked() unconditionally.
2129 // We call getTransactionFlags(), which will also clear the flags,
2130 // with mStateLock held to guarantee that mCurrentState won't change
2131 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002132
Mathias Agopiane57f2922012-08-09 16:29:12 -07002133 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002134 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002135
Mathias Agopianca4d3602011-05-19 15:38:14 -07002136 mLastTransactionTime = systemTime() - now;
2137 mDebugInTransaction = 0;
2138 invalidateHwcGeometry();
2139 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002140}
2141
Lloyd Pique715a2c12017-12-14 17:18:08 -08002142DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002143 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002144 // Figure out whether the event is for the primary display or an
2145 // external display by matching the Hwc display id against one for a
2146 // connected display. If we did not find a match, we then check what
2147 // displays are not already connected to determine the type. If we don't
2148 // have a connected primary display, we assume the new display is meant to
2149 // be the primary display, and then if we don't have an external display,
2150 // we assume it is that.
2151 const auto primaryDisplayId =
2152 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2153 const auto externalDisplayId =
2154 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2155 if (primaryDisplayId && primaryDisplayId == display) {
2156 return DisplayDevice::DISPLAY_PRIMARY;
2157 } else if (externalDisplayId && externalDisplayId == display) {
2158 return DisplayDevice::DISPLAY_EXTERNAL;
2159 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2160 return DisplayDevice::DISPLAY_PRIMARY;
2161 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2162 return DisplayDevice::DISPLAY_EXTERNAL;
2163 }
2164
2165 return DisplayDevice::DISPLAY_ID_INVALID;
2166}
2167
Lloyd Piqueba04e622017-12-14 17:11:26 -08002168void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2169 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002170 auto displayType = determineDisplayType(event.display, event.connection);
2171 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2172 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2173 continue;
2174 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002175
2176 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2177 ALOGE("External displays are not supported by the vr hardware composer.");
2178 continue;
2179 }
2180
Lloyd Pique715a2c12017-12-14 17:18:08 -08002181 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002182
2183 if (event.connection == HWC2::Connection::Connected) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002184 if (!mBuiltinDisplays[displayType].get()) {
2185 ALOGV("Creating built in display %d", displayType);
2186 mBuiltinDisplays[displayType] = new BBinder();
2187 // All non-virtual displays are currently considered secure.
2188 DisplayDeviceState info(displayType, true);
2189 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2190 "Built-in Screen" : "External Screen";
2191 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
2192 mInterceptor->saveDisplayCreation(info);
2193 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002194 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002195 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002196
Lloyd Piquefcd86612017-12-14 17:15:36 -08002197 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2198 if (idx >= 0) {
2199 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Lloyd Pique4dccc412018-01-22 17:21:36 -08002200 mInterceptor->saveDisplayDeletion(info.displayId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002201 mCurrentState.displays.removeItemsAt(idx);
2202 }
2203 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002204 }
2205
2206 processDisplayChangesLocked();
2207 }
2208
2209 mPendingHotplugEvents.clear();
2210}
2211
Lloyd Pique99d3da52018-01-22 17:48:03 -08002212sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2213 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2214 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
2215 bool hasWideColorSupport = false;
2216 if (hasWideColorDisplay) {
2217 std::vector<ColorMode> modes = getHwComposer().getColorModes(state.type);
2218 for (ColorMode colorMode : modes) {
2219 switch (colorMode) {
2220 case ColorMode::DISPLAY_P3:
2221 case ColorMode::ADOBE_RGB:
2222 case ColorMode::DCI_P3:
2223 hasWideColorSupport = true;
2224 break;
2225 default:
2226 break;
2227 }
2228 }
2229 }
2230
2231 bool hasHdrSupport = false;
2232 std::unique_ptr<HdrCapabilities> hdrCapabilities =
2233 getHwComposer().getHdrCapabilities(state.type);
2234 if (hdrCapabilities) {
2235 const std::vector<int32_t> types = hdrCapabilities->getSupportedHdrTypes();
2236 auto iter = std::find(types.cbegin(), types.cend(), HAL_HDR_HDR10);
2237 hasHdrSupport = iter != types.cend();
2238 }
2239
2240 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2241 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2242
2243 /*
2244 * Create our display's surface
2245 */
2246 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2247 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
2248 renderSurface->setAsync(state.type >= DisplayDevice::DISPLAY_VIRTUAL);
2249 renderSurface->setNativeWindow(nativeWindow.get());
2250 const int displayWidth = renderSurface->queryWidth();
2251 const int displayHeight = renderSurface->queryHeight();
2252
2253 // Make sure that composition can never be stalled by a virtual display
2254 // consumer that isn't processing buffers fast enough. We have to do this
2255 // in two places:
2256 // * Here, in case the display is composed entirely by HWC.
2257 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2258 // window's swap interval in eglMakeCurrent, so they'll override the
2259 // interval we set here.
2260 if (state.type >= DisplayDevice::DISPLAY_VIRTUAL) {
2261 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2262 }
2263
2264 // virtual displays are always considered enabled
2265 auto initialPowerMode = (state.type >= DisplayDevice::DISPLAY_VIRTUAL) ? HWC_POWER_MODE_NORMAL
2266 : HWC_POWER_MODE_OFF;
2267
2268 sp<DisplayDevice> hw =
2269 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2270 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
2271 hasWideColorSupport, hasHdrSupport, initialPowerMode);
2272
2273 if (maxFrameBufferAcquiredBuffers >= 3) {
2274 nativeWindowSurface->preallocateBuffers();
2275 }
2276
2277 ColorMode defaultColorMode = ColorMode::NATIVE;
2278 if (hasWideColorSupport) {
2279 defaultColorMode = ColorMode::SRGB;
2280 }
2281 setActiveColorModeInternal(hw, defaultColorMode);
2282 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
2283 hw->setLayerStack(state.layerStack);
2284 hw->setProjection(state.orientation, state.viewport, state.frame);
2285 hw->setDisplayName(state.displayName);
2286
2287 return hw;
2288}
2289
Lloyd Pique347200f2017-12-14 17:00:15 -08002290void SurfaceFlinger::processDisplayChangesLocked() {
2291 // here we take advantage of Vector's copy-on-write semantics to
2292 // improve performance by skipping the transaction entirely when
2293 // know that the lists are identical
2294 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2295 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2296 if (!curr.isIdenticalTo(draw)) {
2297 mVisibleRegionsDirty = true;
2298 const size_t cc = curr.size();
2299 size_t dc = draw.size();
2300
2301 // find the displays that were removed
2302 // (ie: in drawing state but not in current state)
2303 // also handle displays that changed
2304 // (ie: displays that are in both lists)
2305 for (size_t i = 0; i < dc;) {
2306 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2307 if (j < 0) {
2308 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002309 // Call makeCurrent() on the primary display so we can
2310 // be sure that nothing associated with this display
2311 // is current.
2312 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2313 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2314 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2315 if (hw != nullptr) hw->disconnect(getHwComposer());
2316 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2317 mEventThread->onHotplugReceived(draw[i].type, false);
2318 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002319 } else {
2320 // this display is in both lists. see if something changed.
2321 const DisplayDeviceState& state(curr[j]);
2322 const wp<IBinder>& display(curr.keyAt(j));
2323 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2324 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2325 if (state_binder != draw_binder) {
2326 // changing the surface is like destroying and
2327 // recreating the DisplayDevice, so we just remove it
2328 // from the drawing state, so that it get re-added
2329 // below.
2330 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2331 if (hw != nullptr) hw->disconnect(getHwComposer());
2332 mDisplays.removeItem(display);
2333 mDrawingState.displays.removeItemsAt(i);
2334 dc--;
2335 // at this point we must loop to the next item
2336 continue;
2337 }
2338
2339 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2340 if (disp != nullptr) {
2341 if (state.layerStack != draw[i].layerStack) {
2342 disp->setLayerStack(state.layerStack);
2343 }
2344 if ((state.orientation != draw[i].orientation) ||
2345 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2346 disp->setProjection(state.orientation, state.viewport, state.frame);
2347 }
2348 if (state.width != draw[i].width || state.height != draw[i].height) {
2349 disp->setDisplaySize(state.width, state.height);
2350 }
2351 }
2352 }
2353 ++i;
2354 }
2355
2356 // find displays that were added
2357 // (ie: in current state but not in drawing state)
2358 for (size_t i = 0; i < cc; i++) {
2359 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2360 const DisplayDeviceState& state(curr[i]);
2361
2362 sp<DisplaySurface> dispSurface;
2363 sp<IGraphicBufferProducer> producer;
2364 sp<IGraphicBufferProducer> bqProducer;
2365 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002366 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002367
2368 int32_t hwcId = -1;
2369 if (state.isVirtualDisplay()) {
2370 // Virtual displays without a surface are dormant:
2371 // they have external state (layer stack, projection,
2372 // etc.) but no internal state (i.e. a DisplayDevice).
2373 if (state.surface != nullptr) {
2374 // Allow VR composer to use virtual displays.
2375 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2376 int width = 0;
2377 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2378 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2379 int height = 0;
2380 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2381 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2382 int intFormat = 0;
2383 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2384 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2385 auto format = static_cast<android_pixel_format_t>(intFormat);
2386
2387 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2388 }
2389
2390 // TODO: Plumb requested format back up to consumer
2391
2392 sp<VirtualDisplaySurface> vds =
2393 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2394 bqProducer, bqConsumer,
2395 state.displayName);
2396
2397 dispSurface = vds;
2398 producer = vds;
2399 }
2400 } else {
2401 ALOGE_IF(state.surface != nullptr,
2402 "adding a supported display, but rendering "
2403 "surface is provided (%p), ignoring it",
2404 state.surface.get());
2405
2406 hwcId = state.type;
2407 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2408 producer = bqProducer;
2409 }
2410
2411 const wp<IBinder>& display(curr.keyAt(i));
2412 if (dispSurface != nullptr) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002413 mDisplays.add(display,
2414 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2415 producer));
Lloyd Pique347200f2017-12-14 17:00:15 -08002416 if (!state.isVirtualDisplay()) {
2417 mEventThread->onHotplugReceived(state.type, true);
2418 }
2419 }
2420 }
2421 }
2422 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002423
2424 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002425}
2426
Mathias Agopian87baae12012-07-31 12:38:26 -07002427void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002428{
Dan Stoza7dde5992015-05-22 09:51:44 -07002429 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002430 mCurrentState.traverseInZOrder([](Layer* layer) {
2431 layer->notifyAvailableFrames();
2432 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002433
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002434 /*
2435 * Traversal of the children
2436 * (perform the transaction for each of them if needed)
2437 */
2438
Mathias Agopian3559b072012-08-15 13:46:03 -07002439 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002440 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002441 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002442 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002443
2444 const uint32_t flags = layer->doTransaction(0);
2445 if (flags & Layer::eVisibleRegion)
2446 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002447 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002448 }
2449
2450 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002451 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002452 */
2453
Mathias Agopiane57f2922012-08-09 16:29:12 -07002454 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002455 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002456 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002457 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002458
Mathias Agopian84300952012-11-21 16:02:13 -08002459 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2460 // The transform hint might have changed for some layers
2461 // (either because a display has changed, or because a layer
2462 // as changed).
2463 //
2464 // Walk through all the layers in currentLayers,
2465 // and update their transform hint.
2466 //
2467 // If a layer is visible only on a single display, then that
2468 // display is used to calculate the hint, otherwise we use the
2469 // default display.
2470 //
2471 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2472 // the hint is set before we acquire a buffer from the surface texture.
2473 //
2474 // NOTE: layer transactions have taken place already, so we use their
2475 // drawing state. However, SurfaceFlinger's own transaction has not
2476 // happened yet, so we must use the current state layer list
2477 // (soon to become the drawing state list).
2478 //
2479 sp<const DisplayDevice> disp;
2480 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002481 bool first = true;
2482 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002483 // NOTE: we rely on the fact that layers are sorted by
2484 // layerStack first (so we don't have to traverse the list
2485 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002486 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002487 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002488 currentlayerStack = layerStack;
2489 // figure out if this layerstack is mirrored
2490 // (more than one display) if so, pick the default display,
2491 // if not, pick the only display it's on.
2492 disp.clear();
2493 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2494 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002495 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002496 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002497 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002498 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002499 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002500 break;
2501 }
2502 }
2503 }
2504 }
Chet Haase91d25932013-04-11 15:24:55 -07002505
Robert Carr56a0b9a2017-12-04 16:06:13 -08002506 if (transactionFlags & eDisplayTransactionNeeded) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002507 if (disp == nullptr) {
Robert Carr56a0b9a2017-12-04 16:06:13 -08002508 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2509 // redraw after transform hint changes. See bug 8508397.
2510
2511 // could be null when this layer is using a layerStack
2512 // that is not visible on any display. Also can occur at
2513 // screen off/on times.
2514 disp = getDefaultDisplayDeviceLocked();
2515 }
2516 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08002517 }
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002518 if (disp != nullptr) {
2519 layer->updateTransformHint(disp);
2520 }
Robert Carr2047fae2016-11-28 14:09:09 -08002521
2522 first = false;
2523 });
Mathias Agopian84300952012-11-21 16:02:13 -08002524 }
2525
2526
Mathias Agopian3559b072012-08-15 13:46:03 -07002527 /*
2528 * Perform our own transaction if needed
2529 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002530
2531 if (mLayersAdded) {
2532 mLayersAdded = false;
2533 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002534 mVisibleRegionsDirty = true;
2535 }
2536
2537 // some layers might have been removed, so
2538 // we need to update the regions they're exposing.
2539 if (mLayersRemoved) {
2540 mLayersRemoved = false;
2541 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002542 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002543 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002544 // this layer is not visible anymore
2545 // TODO: we could traverse the tree from front to back and
2546 // compute the actual visible region
2547 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002548 Region visibleReg;
2549 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002550 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002551 }
Robert Carr2047fae2016-11-28 14:09:09 -08002552 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002553 }
2554
2555 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002556
2557 updateCursorAsync();
2558}
2559
2560void SurfaceFlinger::updateCursorAsync()
2561{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002562 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2563 auto& displayDevice = mDisplays[displayId];
2564 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002565 continue;
2566 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002567
2568 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2569 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002570 }
2571 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002572}
2573
2574void SurfaceFlinger::commitTransaction()
2575{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002576 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002577 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002578 for (const auto& l : mLayersPendingRemoval) {
2579 recordBufferingStats(l->getName().string(),
2580 l->getOccupancyHistory(true));
2581 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002582 }
2583 mLayersPendingRemoval.clear();
2584 }
2585
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002586 // If this transaction is part of a window animation then the next frame
2587 // we composite should be considered an animation as well.
2588 mAnimCompositionPending = mAnimTransactionPending;
2589
Mathias Agopian4fec8732012-06-29 14:12:52 -07002590 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002591 mDrawingState.traverseInZOrder([](Layer* layer) {
2592 layer->commitChildList();
2593 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002594 mTransactionPending = false;
2595 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002596 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002597}
2598
Chia-I Wuab0c3192017-08-01 11:29:00 -07002599void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002600 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002601{
Mathias Agopian841cde52012-03-01 15:44:37 -08002602 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002603 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002604
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002605 Region aboveOpaqueLayers;
2606 Region aboveCoveredLayers;
2607 Region dirty;
2608
Mathias Agopian87baae12012-07-31 12:38:26 -07002609 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002610
Robert Carr2047fae2016-11-28 14:09:09 -08002611 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002612 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002613 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002614
Jesse Hall01e29052013-02-19 16:13:35 -08002615 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002616 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002617 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002618
Mathias Agopianab028732010-03-16 16:41:46 -07002619 /*
2620 * opaqueRegion: area of a surface that is fully opaque.
2621 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002622 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002623
2624 /*
2625 * visibleRegion: area of a surface that is visible on screen
2626 * and not fully transparent. This is essentially the layer's
2627 * footprint minus the opaque regions above it.
2628 * Areas covered by a translucent surface are considered visible.
2629 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002630 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002631
2632 /*
2633 * coveredRegion: area of a surface that is covered by all
2634 * visible regions above it (which includes the translucent areas).
2635 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002636 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002637
Jesse Halla8026d22012-09-25 13:25:04 -07002638 /*
2639 * transparentRegion: area of a surface that is hinted to be completely
2640 * transparent. This is only used to tell when the layer has no visible
2641 * non-transparent regions and can be removed from the layer list. It
2642 * does not affect the visibleRegion of this layer or any layers
2643 * beneath it. The hint may not be correct if apps don't respect the
2644 * SurfaceView restrictions (which, sadly, some don't).
2645 */
2646 Region transparentRegion;
2647
Mathias Agopianab028732010-03-16 16:41:46 -07002648
2649 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002650 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002651 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002652 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002653 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002654 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002655 if (!visibleRegion.isEmpty()) {
2656 // Remove the transparent area from the visible region
2657 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002658 if (tr.preserveRects()) {
2659 // transform the transparent region
2660 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002661 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002662 // transformation too complex, can't do the
2663 // transparent region optimization.
2664 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002665 }
Mathias Agopianab028732010-03-16 16:41:46 -07002666 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002667
Mathias Agopianab028732010-03-16 16:41:46 -07002668 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002669 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002670 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002671 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2672 // the opaque region is the layer's footprint
2673 opaqueRegion = visibleRegion;
2674 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002675 }
2676 }
2677
Robert Carre5f4f692018-01-12 13:12:28 -08002678 if (visibleRegion.isEmpty()) {
2679 layer->clearVisibilityRegions();
2680 return;
2681 }
2682
Mathias Agopianab028732010-03-16 16:41:46 -07002683 // Clip the covered region to the visible region
2684 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2685
2686 // Update aboveCoveredLayers for next (lower) layer
2687 aboveCoveredLayers.orSelf(visibleRegion);
2688
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002689 // subtract the opaque region covered by the layers above us
2690 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002691
2692 // compute this layer's dirty region
2693 if (layer->contentDirty) {
2694 // we need to invalidate the whole region
2695 dirty = visibleRegion;
2696 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002697 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002698 layer->contentDirty = false;
2699 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002700 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002701 * the exposed region consists of two components:
2702 * 1) what's VISIBLE now and was COVERED before
2703 * 2) what's EXPOSED now less what was EXPOSED before
2704 *
2705 * note that (1) is conservative, we start with the whole
2706 * visible region but only keep what used to be covered by
2707 * something -- which mean it may have been exposed.
2708 *
2709 * (2) handles areas that were not covered by anything but got
2710 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002711 */
Mathias Agopianab028732010-03-16 16:41:46 -07002712 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002713 const Region oldVisibleRegion = layer->visibleRegion;
2714 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002715 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2716 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002717 }
2718 dirty.subtractSelf(aboveOpaqueLayers);
2719
2720 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002721 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002722
Mathias Agopianab028732010-03-16 16:41:46 -07002723 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002724 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002725
Jesse Halla8026d22012-09-25 13:25:04 -07002726 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002727 layer->setVisibleRegion(visibleRegion);
2728 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002729 layer->setVisibleNonTransparentRegion(
2730 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002731 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002732
Mathias Agopian87baae12012-07-31 12:38:26 -07002733 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002734}
2735
Chia-I Wuab0c3192017-08-01 11:29:00 -07002736void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002737 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002738 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002739 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002740 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002741 }
2742 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002743}
2744
Dan Stoza6b9454d2014-11-07 16:00:59 -08002745bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002746{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002747 ALOGV("handlePageFlip");
2748
Brian Andersond6927fb2016-07-23 23:37:30 -07002749 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002750
Mathias Agopian4fec8732012-06-29 14:12:52 -07002751 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002752 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002753 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002754
2755 // Store the set of layers that need updates. This set must not change as
2756 // buffers are being latched, as this could result in a deadlock.
2757 // Example: Two producers share the same command stream and:
2758 // 1.) Layer 0 is latched
2759 // 2.) Layer 0 gets a new frame
2760 // 2.) Layer 1 gets a new frame
2761 // 3.) Layer 1 is latched.
2762 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2763 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002764 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002765 if (layer->hasQueuedFrame()) {
2766 frameQueued = true;
2767 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002768 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002769 } else {
2770 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002771 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002772 } else {
2773 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002774 }
Robert Carr2047fae2016-11-28 14:09:09 -08002775 });
2776
Dan Stoza9e56aa02015-11-02 13:00:03 -08002777 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002778 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002779 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002780 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002781 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002782 newDataLatched = true;
2783 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002784 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002785
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002786 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002787
2788 // If we will need to wake up at some time in the future to deal with a
2789 // queued frame that shouldn't be displayed during this vsync period, wake
2790 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002791 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002792 signalLayerUpdate();
2793 }
2794
2795 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002796 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002797}
2798
Mathias Agopianad456f92011-01-13 17:53:01 -08002799void SurfaceFlinger::invalidateHwcGeometry()
2800{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002801 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002802}
2803
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002804
Fabien Sanglard830b8472016-11-30 16:35:58 -08002805void SurfaceFlinger::doDisplayComposition(
2806 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002807 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002808{
Dan Stoza71433162014-02-04 16:22:36 -08002809 // We only need to actually compose the display if:
2810 // 1) It is being handled by hardware composer, which may need this to
2811 // keep its virtual display state machine in sync, or
2812 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002813 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002814 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002815 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002816 return;
2817 }
2818
Dan Stoza9e56aa02015-11-02 13:00:03 -08002819 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002820 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002821
2822 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002823 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002824}
2825
Chia-I Wub02087d2017-11-09 10:19:54 -08002826bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002827{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002828 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002829
Chia-I Wub02087d2017-11-09 10:19:54 -08002830 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002831 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002832 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002833
2834 mat4 oldColorMatrix;
David Sodman105b7dc2017-11-04 20:28:14 -07002835 const bool applyColorMatrix = !getBE().mHwc->hasDeviceComposition(hwcId) &&
2836 !getBE().mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002837 if (applyColorMatrix) {
2838 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2839 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2840 }
2841
David Sodman105b7dc2017-11-04 20:28:14 -07002842 bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
David Sodman4b7c4bc2017-11-17 12:13:59 -08002843 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002844 if (hasClientComposition) {
2845 ALOGV("hasClientComposition");
2846
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002847 android_dataspace outputDataspace = HAL_DATASPACE_UNKNOWN;
Chia-I Wu9a48a8c2018-02-20 14:27:30 -08002848 if (displayDevice->getWideColorSupport() &&
Peiyong Lina52f0292018-03-14 17:26:31 -07002849 displayDevice->getActiveColorMode() == ColorMode::DISPLAY_P3) {
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002850 outputDataspace = HAL_DATASPACE_DISPLAY_P3;
2851 }
2852 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
2853
Chia-I Wu7f402902017-11-09 12:51:10 -08002854 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002855 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002856 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002857 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002858
2859 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002860 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002861 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2862 }
2863 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002864 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002865
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002866 // Never touch the framebuffer if we don't have any framebuffer layers
David Sodman105b7dc2017-11-04 20:28:14 -07002867 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002868 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002869 // when using overlays, we assume a fully transparent framebuffer
2870 // NOTE: we could reduce how much we need to clear, for instance
2871 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002872 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002873 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002874 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002875 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002876 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002877 // we're left with the letterbox region
2878 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002879 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002880
2881 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002882 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002883
Mathias Agopianb9494d52012-04-18 02:28:45 -07002884 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002885 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002886 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002887 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002888 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002889 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002890
Dan Stoza9e56aa02015-11-02 13:00:03 -08002891 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002892 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002893 // scissor on the main display. It should never be needed
2894 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002895 const Rect& bounds(displayDevice->getBounds());
2896 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002897 if (scissor != bounds) {
2898 // scissor doesn't match the screen's dimensions, so we
2899 // need to clear everything outside of it and enable
2900 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002901
Mathias Agopianf45c5102012-10-24 16:29:17 -07002902 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002903 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002904 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002905 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002906 }
2907 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002908 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002909
Mathias Agopian85d751c2012-08-29 16:59:24 -07002910 /*
2911 * and then, render the layers targeted at the framebuffer
2912 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002913
Dan Stoza9e56aa02015-11-02 13:00:03 -08002914 ALOGV("Rendering client layers");
2915 const Transform& displayTransform = displayDevice->getTransform();
2916 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002917 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002918 bool firstLayer = true;
2919 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002920 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002921 displayTransform.transform(layer->visibleRegion)));
2922 ALOGV("Layer: %s", layer->getName().string());
2923 ALOGV(" Composition type: %s",
2924 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002925 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002926 switch (layer->getCompositionType(hwcId)) {
2927 case HWC2::Composition::Cursor:
2928 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002929 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002930 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002931 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002932 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002933 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002934 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002935 // never clear the very first layer since we're
2936 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002937 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002938 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002939 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002940 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002941 case HWC2::Composition::Client: {
chaviwa76b2712017-09-20 12:02:26 -07002942 layer->draw(renderArea, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002943 break;
2944 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002945 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002946 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002947 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002948 } else {
2949 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002950 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002951 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002952 }
2953 } else {
2954 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002955 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002956 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002957 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002958 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07002959 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002960 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002961 }
2962 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002963
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002964 if (applyColorMatrix) {
2965 getRenderEngine().setupColorTransform(oldColorMatrix);
2966 }
2967
Mathias Agopianf45c5102012-10-24 16:29:17 -07002968 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002969 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002970 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002971}
2972
Fabien Sanglard830b8472016-11-30 16:35:58 -08002973void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2974 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08002975 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07002976 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002977}
2978
Dan Stoza7d89d062015-04-30 13:29:25 -07002979status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002980 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002981 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002982 const sp<Layer>& lbc,
2983 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002984{
Dan Stoza7d89d062015-04-30 13:29:25 -07002985 // add this layer to the current state list
2986 {
2987 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002988 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002989 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2990 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002991 return NO_MEMORY;
2992 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002993 if (parent == nullptr) {
2994 mCurrentState.layersSortedByZ.add(lbc);
2995 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08002996 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002997 ALOGE("addClientLayer called with a removed parent");
2998 return NAME_NOT_FOUND;
2999 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003000 parent->addChild(lbc);
3001 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003002
Dan Stoza101d8dc2018-02-27 15:42:25 -08003003 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
Dan Stoza0a0158c2018-03-16 13:38:54 -07003004 // TODO (b/74616334): Change this back to a fatal assert once the leak is fixed
3005 ALOGE_IF(mGraphicBufferProducerList.size() > mMaxGraphicBufferProducerListSize,
3006 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3007 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize,
3008 mNumLayers);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003009 mLayersAdded = true;
3010 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003011 }
3012
Mathias Agopian96f08192010-06-02 23:28:45 -07003013 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003014 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003015
Dan Stoza7d89d062015-04-30 13:29:25 -07003016 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003017}
3018
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003019status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003020 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003021 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3022}
Robert Carr7f9b8992017-03-10 11:08:39 -08003023
chaviwca27f252018-02-06 16:46:39 -08003024status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3025 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003026 if (layer->isPendingRemoval()) {
3027 return NO_ERROR;
3028 }
3029
Robert Carr1f0a16a2016-10-24 16:27:39 -07003030 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003031 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003032 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003033 if (topLevelOnly) {
3034 return NO_ERROR;
3035 }
3036
Chia-I Wu98f1c102017-05-30 14:54:08 -07003037 sp<Layer> ancestor = p;
3038 while (ancestor->getParent() != nullptr) {
3039 ancestor = ancestor->getParent();
3040 }
3041 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3042 ALOGE("removeLayer called with a layer whose parent has been removed");
3043 return NAME_NOT_FOUND;
3044 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003045
3046 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003047 } else {
3048 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003049 }
3050
Robert Carr136e2f62017-02-08 17:54:29 -08003051 // As a matter of normal operation, the LayerCleaner will produce a second
3052 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3053 // so we will succeed in promoting it, but it's already been removed
3054 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3055 // otherwise something has gone wrong and we are leaking the layer.
3056 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003057 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3058 layer->getName().string(),
3059 (p != nullptr) ? p->getName().string() : "no-parent");
3060 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003061 } else if (index < 0) {
3062 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003063 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003064
Chia-I Wuc6657022017-08-15 11:18:17 -07003065 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003066 mLayersPendingRemoval.add(layer);
3067 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003068 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003069 setTransactionFlags(eTransactionNeeded);
3070 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003071}
3072
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003073uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003074 return android_atomic_release_load(&mTransactionFlags);
3075}
3076
Mathias Agopian3f844832013-08-07 21:24:32 -07003077uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003078 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3079}
3080
Mathias Agopian3f844832013-08-07 21:24:32 -07003081uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003082 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
3083 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003084 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003085 }
3086 return old;
3087}
3088
chaviwca27f252018-02-06 16:46:39 -08003089bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3090 for (const ComposerState& state : states) {
3091 // Here we need to check that the interface we're given is indeed
3092 // one of our own. A malicious client could give us a nullptr
3093 // IInterface, or one of its own or even one of our own but a
3094 // different type. All these situations would cause us to crash.
3095 if (state.client == nullptr) {
3096 return true;
3097 }
3098
3099 sp<IBinder> binder = IInterface::asBinder(state.client);
3100 if (binder == nullptr) {
3101 return true;
3102 }
3103
3104 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3105 return true;
3106 }
3107 }
3108 return false;
3109}
3110
Mathias Agopian8b33f032012-07-24 20:43:54 -07003111void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003112 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003113 const Vector<DisplayState>& displays,
3114 uint32_t flags)
3115{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003116 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003117 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003118 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003119
chaviwca27f252018-02-06 16:46:39 -08003120 if (containsAnyInvalidClientState(states)) {
3121 return;
3122 }
3123
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003124 if (flags & eAnimation) {
3125 // For window updates that are part of an animation we must wait for
3126 // previous animation "frames" to be handled.
3127 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003128 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003129 if (CC_UNLIKELY(err != NO_ERROR)) {
3130 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003131 // caller after a few seconds.
3132 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3133 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003134 mAnimTransactionPending = false;
3135 break;
3136 }
3137 }
3138 }
3139
chaviwca27f252018-02-06 16:46:39 -08003140 for (const DisplayState& display : displays) {
3141 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003142 }
3143
chaviwca27f252018-02-06 16:46:39 -08003144 for (const ComposerState& state : states) {
3145 transactionFlags |= setClientStateLocked(state);
3146 }
3147
3148 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3149 // as destroyed should only occur after setting all other states. This is to allow for a
3150 // child re-parent to happen before marking its original parent as destroyed (which would
3151 // then mark the child as destroyed).
3152 for (const ComposerState& state : states) {
3153 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003154 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003155
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003156 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3157 // anyway. This can be used as a flush mechanism for previous async transactions.
3158 // Empty animation transaction can be used to simulate back-pressure, so also force a
3159 // transaction for empty animation transactions.
3160 if (transactionFlags == 0 &&
3161 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003162 transactionFlags = eTransactionNeeded;
3163 }
3164
Mathias Agopian386aa982011-11-07 21:58:03 -08003165 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003166 if (mInterceptor->isEnabled()) {
3167 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003168 }
Irvel468051e2016-06-13 16:44:44 -07003169
Mathias Agopian386aa982011-11-07 21:58:03 -08003170 // this triggers the transaction
3171 setTransactionFlags(transactionFlags);
3172
3173 // if this is a synchronous transaction, wait for it to take effect
3174 // before returning.
3175 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003176 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003177 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003178 if (flags & eAnimation) {
3179 mAnimTransactionPending = true;
3180 }
3181 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003182 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3183 if (CC_UNLIKELY(err != NO_ERROR)) {
3184 // just in case something goes wrong in SF, return to the
3185 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003186 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3187 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003188 break;
3189 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003190 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003191 }
3192}
3193
Mathias Agopiane57f2922012-08-09 16:29:12 -07003194uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3195{
Jesse Hall9a143922012-10-04 16:29:19 -07003196 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3197 if (dpyIdx < 0)
3198 return 0;
3199
Mathias Agopiane57f2922012-08-09 16:29:12 -07003200 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003201 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003202 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003203 const uint32_t what = s.what;
3204 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003205 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003206 disp.surface = s.surface;
3207 flags |= eDisplayTransactionNeeded;
3208 }
3209 }
3210 if (what & DisplayState::eLayerStackChanged) {
3211 if (disp.layerStack != s.layerStack) {
3212 disp.layerStack = s.layerStack;
3213 flags |= eDisplayTransactionNeeded;
3214 }
3215 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003216 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003217 if (disp.orientation != s.orientation) {
3218 disp.orientation = s.orientation;
3219 flags |= eDisplayTransactionNeeded;
3220 }
3221 if (disp.frame != s.frame) {
3222 disp.frame = s.frame;
3223 flags |= eDisplayTransactionNeeded;
3224 }
3225 if (disp.viewport != s.viewport) {
3226 disp.viewport = s.viewport;
3227 flags |= eDisplayTransactionNeeded;
3228 }
3229 }
Michael Lentine47e45402014-07-18 15:34:25 -07003230 if (what & DisplayState::eDisplaySizeChanged) {
3231 if (disp.width != s.width) {
3232 disp.width = s.width;
3233 flags |= eDisplayTransactionNeeded;
3234 }
3235 if (disp.height != s.height) {
3236 disp.height = s.height;
3237 flags |= eDisplayTransactionNeeded;
3238 }
3239 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003240 }
3241 return flags;
3242}
3243
chaviwca27f252018-02-06 16:46:39 -08003244uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3245 const layer_state_t& s = composerState.state;
3246 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3247
Mathias Agopian13127d82013-03-05 17:47:11 -08003248 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003249 if (layer == nullptr) {
3250 return 0;
3251 }
3252
3253 if (layer->isPendingRemoval()) {
3254 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3255 return 0;
3256 }
3257
3258 uint32_t flags = 0;
3259
3260 const uint32_t what = s.what;
3261 bool geometryAppliesWithResize =
3262 what & layer_state_t::eGeometryAppliesWithResize;
3263 if (what & layer_state_t::ePositionChanged) {
3264 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3265 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003266 }
chaviw8b3871a2017-11-01 17:41:01 -07003267 }
3268 if (what & layer_state_t::eLayerChanged) {
3269 // NOTE: index needs to be calculated before we update the state
3270 const auto& p = layer->getParent();
3271 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003272 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003273 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003274 mCurrentState.layersSortedByZ.removeAt(idx);
3275 mCurrentState.layersSortedByZ.add(layer);
3276 // we need traversal (state changed)
3277 // AND transaction (list changed)
3278 flags |= eTransactionNeeded|eTraversalNeeded;
3279 }
chaviw8b3871a2017-11-01 17:41:01 -07003280 } else {
3281 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003282 flags |= eTransactionNeeded|eTraversalNeeded;
3283 }
3284 }
chaviw8b3871a2017-11-01 17:41:01 -07003285 }
3286 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003287 // NOTE: index needs to be calculated before we update the state
3288 const auto& p = layer->getParent();
3289 if (p == nullptr) {
3290 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3291 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3292 mCurrentState.layersSortedByZ.removeAt(idx);
3293 mCurrentState.layersSortedByZ.add(layer);
3294 // we need traversal (state changed)
3295 // AND transaction (list changed)
3296 flags |= eTransactionNeeded|eTraversalNeeded;
3297 }
3298 } else {
3299 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3300 flags |= eTransactionNeeded|eTraversalNeeded;
3301 }
chaviw8b3871a2017-11-01 17:41:01 -07003302 }
3303 }
3304 if (what & layer_state_t::eSizeChanged) {
3305 if (layer->setSize(s.w, s.h)) {
3306 flags |= eTraversalNeeded;
3307 }
3308 }
3309 if (what & layer_state_t::eAlphaChanged) {
3310 if (layer->setAlpha(s.alpha))
3311 flags |= eTraversalNeeded;
3312 }
3313 if (what & layer_state_t::eColorChanged) {
3314 if (layer->setColor(s.color))
3315 flags |= eTraversalNeeded;
3316 }
3317 if (what & layer_state_t::eMatrixChanged) {
3318 if (layer->setMatrix(s.matrix))
3319 flags |= eTraversalNeeded;
3320 }
3321 if (what & layer_state_t::eTransparentRegionChanged) {
3322 if (layer->setTransparentRegionHint(s.transparentRegion))
3323 flags |= eTraversalNeeded;
3324 }
3325 if (what & layer_state_t::eFlagsChanged) {
3326 if (layer->setFlags(s.flags, s.mask))
3327 flags |= eTraversalNeeded;
3328 }
3329 if (what & layer_state_t::eCropChanged) {
3330 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3331 flags |= eTraversalNeeded;
3332 }
3333 if (what & layer_state_t::eFinalCropChanged) {
3334 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3335 flags |= eTraversalNeeded;
3336 }
3337 if (what & layer_state_t::eLayerStackChanged) {
3338 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3339 // We only allow setting layer stacks for top level layers,
3340 // everything else inherits layer stack from its parent.
3341 if (layer->hasParent()) {
3342 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3343 layer->getName().string());
3344 } else if (idx < 0) {
3345 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3346 "that also does not appear in the top level layer list. Something"
3347 " has gone wrong.", layer->getName().string());
3348 } else if (layer->setLayerStack(s.layerStack)) {
3349 mCurrentState.layersSortedByZ.removeAt(idx);
3350 mCurrentState.layersSortedByZ.add(layer);
3351 // we need traversal (state changed)
3352 // AND transaction (list changed)
3353 flags |= eTransactionNeeded|eTraversalNeeded;
3354 }
3355 }
3356 if (what & layer_state_t::eDeferTransaction) {
3357 if (s.barrierHandle != nullptr) {
3358 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3359 } else if (s.barrierGbp != nullptr) {
3360 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3361 if (authenticateSurfaceTextureLocked(gbp)) {
3362 const auto& otherLayer =
3363 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3364 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3365 } else {
3366 ALOGE("Attempt to defer transaction to to an"
3367 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003368 }
3369 }
chaviw8b3871a2017-11-01 17:41:01 -07003370 // We don't trigger a traversal here because if no other state is
3371 // changed, we don't want this to cause any more work
3372 }
3373 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003374 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003375 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003376 if (!hadParent) {
3377 mCurrentState.layersSortedByZ.remove(layer);
3378 }
chaviw8b3871a2017-11-01 17:41:01 -07003379 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003380 }
chaviw8b3871a2017-11-01 17:41:01 -07003381 }
3382 if (what & layer_state_t::eReparentChildren) {
3383 if (layer->reparentChildren(s.reparentHandle)) {
3384 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003385 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003386 }
chaviw8b3871a2017-11-01 17:41:01 -07003387 if (what & layer_state_t::eDetachChildren) {
3388 layer->detachChildren();
3389 }
3390 if (what & layer_state_t::eOverrideScalingModeChanged) {
3391 layer->setOverrideScalingMode(s.overrideScalingMode);
3392 // We don't trigger a traversal here because if no other state is
3393 // changed, we don't want this to cause any more work
3394 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003395 return flags;
3396}
3397
chaviwca27f252018-02-06 16:46:39 -08003398void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3399 const layer_state_t& state = composerState.state;
3400 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3401
3402 sp<Layer> layer(client->getLayerUser(state.surface));
3403 if (layer == nullptr) {
3404 return;
3405 }
3406
3407 if (layer->isPendingRemoval()) {
3408 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3409 return;
3410 }
3411
3412 if (state.what & layer_state_t::eDestroySurface) {
3413 removeLayerLocked(mStateLock, layer);
3414 }
3415}
3416
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003417status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003418 const String8& name,
3419 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003420 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003421 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3422 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003423{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003424 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003425 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003426 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003427 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003428 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003429
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003430 status_t result = NO_ERROR;
3431
3432 sp<Layer> layer;
3433
Cody Northropbc755282017-03-31 12:00:08 -06003434 String8 uniqueName = getUniqueLayerName(name);
3435
Mathias Agopian3165cc22012-08-08 19:42:09 -07003436 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3437 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003438 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003439 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003440 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003441
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003442 break;
chaviw13fdc492017-06-27 12:40:18 -07003443 case ISurfaceComposerClient::eFXSurfaceColor:
3444 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003445 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003446 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003447 break;
3448 default:
3449 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003450 break;
3451 }
3452
Dan Stoza7d89d062015-04-30 13:29:25 -07003453 if (result != NO_ERROR) {
3454 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003455 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003456
Chia-I Wuab0c3192017-08-01 11:29:00 -07003457 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3458 // TODO b/64227542
3459 if (windowType == 441731) {
3460 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3461 layer->setPrimaryDisplayOnly();
3462 }
3463
Albert Chaulk479c60c2017-01-27 14:21:34 -05003464 layer->setInfo(windowType, ownerUid);
3465
Robert Carr1f0a16a2016-10-24 16:27:39 -07003466 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003467 if (result != NO_ERROR) {
3468 return result;
3469 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003470 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003471
3472 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003473 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003474}
3475
Cody Northropbc755282017-03-31 12:00:08 -06003476String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3477{
3478 bool matchFound = true;
3479 uint32_t dupeCounter = 0;
3480
3481 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3482 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3483
3484 // Loop over layers until we're sure there is no matching name
3485 while (matchFound) {
3486 matchFound = false;
3487 mDrawingState.traverseInZOrder([&](Layer* layer) {
3488 if (layer->getName() == uniqueName) {
3489 matchFound = true;
3490 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3491 }
3492 });
3493 }
3494
3495 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3496
3497 return uniqueName;
3498}
3499
David Sodman0c69cad2017-08-21 12:12:51 -07003500status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003501 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3502 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003503{
3504 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003505 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003506 case PIXEL_FORMAT_TRANSPARENT:
3507 case PIXEL_FORMAT_TRANSLUCENT:
3508 format = PIXEL_FORMAT_RGBA_8888;
3509 break;
3510 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003511 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003512 break;
3513 }
3514
David Sodman0c69cad2017-08-21 12:12:51 -07003515 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3516 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003517 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003518 *handle = layer->getHandle();
3519 *gbp = layer->getProducer();
3520 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003521 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003522
David Sodman0c69cad2017-08-21 12:12:51 -07003523 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003524 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003525}
3526
chaviw13fdc492017-06-27 12:40:18 -07003527status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003528 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003529 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003530{
chaviw13fdc492017-06-27 12:40:18 -07003531 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003532 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003533 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003534}
3535
Mathias Agopianac9fa422013-02-11 16:40:36 -08003536status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003537{
Robert Carr9524cb32017-02-13 11:32:32 -08003538 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003539 status_t err = NO_ERROR;
3540 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003541 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003542 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003543 err = removeLayer(l);
3544 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3545 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003546 }
3547 return err;
3548}
3549
Mathias Agopian13127d82013-03-05 17:47:11 -08003550status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003551{
Mathias Agopian67106042013-03-14 19:18:13 -07003552 // called by ~LayerCleaner() when all references to the IBinder (handle)
3553 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003554 sp<Layer> l = layer.promote();
3555 if (l == nullptr) {
3556 // The layer has already been removed, carry on
3557 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003558 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003559 // If we have a parent, then we can continue to live as long as it does.
3560 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003561}
3562
Mathias Agopianb60314a2012-04-10 22:09:54 -07003563// ---------------------------------------------------------------------------
3564
Andy McFadden13a082e2012-08-24 10:16:42 -07003565void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003566 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003567 Vector<ComposerState> state;
3568 Vector<DisplayState> displays;
3569 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003570 d.what = DisplayState::eDisplayProjectionChanged |
3571 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003572 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003573 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003574 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003575 d.frame.makeInvalid();
3576 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003577 d.width = 0;
3578 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003579 displays.add(d);
3580 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003581 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3582 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003583
David Sodman105b7dc2017-11-04 20:28:14 -07003584 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003585 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003586 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003587
Brian Andersond0010582017-03-07 13:20:31 -08003588 // Use phase of 0 since phase is not known.
3589 // Use latency of 0, which will snap to the ideal latency.
3590 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003591}
3592
3593void SurfaceFlinger::initializeDisplays() {
3594 class MessageScreenInitialized : public MessageBase {
3595 SurfaceFlinger* flinger;
3596 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003597 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003598 virtual bool handler() {
3599 flinger->onInitializeDisplays();
3600 return true;
3601 }
3602 };
3603 sp<MessageBase> msg = new MessageScreenInitialized(this);
3604 postMessageAsync(msg); // we may be called from main thread, use async message
3605}
3606
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003607void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003608 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003609 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3610 this);
3611 int32_t type = hw->getDisplayType();
3612 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003613
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003614 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003615 return;
3616 }
3617
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003618 hw->setPowerMode(mode);
3619 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3620 ALOGW("Trying to set power mode for virtual display");
3621 return;
3622 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003623
Lloyd Pique4dccc412018-01-22 17:21:36 -08003624 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003625 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003626 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3627 if (idx < 0) {
3628 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3629 return;
3630 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003631 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003632 }
3633
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003634 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003635 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003636 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003637 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3638 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003639 // FIXME: eventthread only knows about the main display right now
3640 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003641 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003642 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003643
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003644 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003645 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003646 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003647
3648 struct sched_param param = {0};
3649 param.sched_priority = 1;
3650 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3651 ALOGW("Couldn't set SCHED_FIFO on display on");
3652 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003653 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003654 // Turn off the display
3655 struct sched_param param = {0};
3656 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3657 ALOGW("Couldn't set SCHED_OTHER on display off");
3658 }
3659
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003660 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3661 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003662 disableHardwareVsync(true); // also cancels any in-progress resync
3663
Mathias Agopiancde87a32012-09-13 14:09:01 -07003664 // FIXME: eventthread only knows about the main display right now
3665 mEventThread->onScreenReleased();
3666 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003667
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003668 getHwComposer().setPowerMode(type, mode);
3669 mVisibleRegionsDirty = true;
3670 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003671 } else if (mode == HWC_POWER_MODE_DOZE ||
3672 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003673 // Update display while dozing
3674 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003675 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3676 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003677 // FIXME: eventthread only knows about the main display right now
3678 mEventThread->onScreenAcquired();
3679 resyncToHardwareVsync(true);
3680 }
3681 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3682 // Leave display going to doze
3683 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3684 disableHardwareVsync(true); // also cancels any in-progress resync
3685 // FIXME: eventthread only knows about the main display right now
3686 mEventThread->onScreenReleased();
3687 }
3688 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003689 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003690 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003691 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003692 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003693}
3694
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003695void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3696 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003697 SurfaceFlinger& mFlinger;
3698 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003699 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003700 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003701 MessageSetPowerMode(SurfaceFlinger& flinger,
3702 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3703 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003704 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003705 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003706 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003707 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003708 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003709 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003710 ALOGW("Attempt to set power mode = %d for virtual display",
3711 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003712 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003713 mFlinger.setPowerModeInternal(
3714 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003715 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003716 return true;
3717 }
3718 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003719 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003720 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003721}
3722
3723// ---------------------------------------------------------------------------
3724
Lloyd Pique755e3192018-01-31 16:46:15 -08003725status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3726 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003727 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003728
Mathias Agopianbd115332013-04-18 16:41:04 -07003729 IPCThreadState* ipc = IPCThreadState::self();
3730 const int pid = ipc->getCallingPid();
3731 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003732
Mathias Agopianbd115332013-04-18 16:41:04 -07003733 if ((uid != AID_SHELL) &&
3734 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003735 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003736 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003737 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003738 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003739 // (this would indicate SF is stuck, but we want to be able to
3740 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003741 status_t err = mStateLock.timedLock(s2ns(1));
3742 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003743 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003744 result.appendFormat(
3745 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3746 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003747 }
3748
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003749 bool dumpAll = true;
3750 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003751 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003752
3753 if (asProto) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003754 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviwa3d7bd32017-11-03 09:41:53 -07003755 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3756 dumpAll = false;
3757 }
3758
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003759 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003760 if ((index < numArgs) &&
3761 (args[index] == String16("--list"))) {
3762 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003763 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003764 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003765 }
3766
3767 if ((index < numArgs) &&
3768 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003769 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003770 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003771 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003772 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003773
3774 if ((index < numArgs) &&
3775 (args[index] == String16("--latency-clear"))) {
3776 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003777 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003778 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003779 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003780
3781 if ((index < numArgs) &&
3782 (args[index] == String16("--dispsync"))) {
3783 index++;
3784 mPrimaryDispSync.dump(result);
3785 dumpAll = false;
3786 }
Dan Stozab90cf072015-03-05 11:05:59 -08003787
3788 if ((index < numArgs) &&
3789 (args[index] == String16("--static-screen"))) {
3790 index++;
3791 dumpStaticScreenStats(result);
3792 dumpAll = false;
3793 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003794
3795 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003796 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003797 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003798 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003799 dumpAll = false;
3800 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003801
3802 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3803 index++;
3804 dumpWideColorInfo(result);
3805 dumpAll = false;
3806 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003807
3808 if ((index < numArgs) &&
3809 (args[index] == String16("--enable-layer-stats"))) {
3810 index++;
3811 mLayerStats.enable();
3812 dumpAll = false;
3813 }
3814
3815 if ((index < numArgs) &&
3816 (args[index] == String16("--disable-layer-stats"))) {
3817 index++;
3818 mLayerStats.disable();
3819 dumpAll = false;
3820 }
3821
3822 if ((index < numArgs) &&
3823 (args[index] == String16("--clear-layer-stats"))) {
3824 index++;
3825 mLayerStats.clear();
3826 dumpAll = false;
3827 }
3828
3829 if ((index < numArgs) &&
3830 (args[index] == String16("--dump-layer-stats"))) {
3831 index++;
3832 mLayerStats.dump(result);
3833 dumpAll = false;
3834 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003835 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003836
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003837 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003838 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003839 }
3840
Mathias Agopian9795c422009-08-26 16:36:26 -07003841 if (locked) {
3842 mStateLock.unlock();
3843 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003844 }
3845 write(fd, result.string(), result.size());
3846 return NO_ERROR;
3847}
3848
Dan Stozac7014012014-02-14 15:03:43 -08003849void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3850 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003851{
Robert Carr2047fae2016-11-28 14:09:09 -08003852 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003853 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003854 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003855}
3856
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003857void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003858 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003859{
3860 String8 name;
3861 if (index < args.size()) {
3862 name = String8(args[index]);
3863 index++;
3864 }
3865
David Sodman105b7dc2017-11-04 20:28:14 -07003866 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003867 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003868 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003869
3870 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003871 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003872 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003873 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003874 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003875 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003876 }
Robert Carr2047fae2016-11-28 14:09:09 -08003877 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003878 }
3879}
3880
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003881void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003882 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003883{
3884 String8 name;
3885 if (index < args.size()) {
3886 name = String8(args[index]);
3887 index++;
3888 }
3889
Robert Carr2047fae2016-11-28 14:09:09 -08003890 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003891 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003892 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003893 }
Robert Carr2047fae2016-11-28 14:09:09 -08003894 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003895
Svetoslavd85084b2014-03-20 10:28:31 -07003896 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003897}
3898
Jamie Gennis6547ff42013-07-16 20:12:42 -07003899// This should only be called from the main thread. Otherwise it would need
3900// the lock and should use mCurrentState rather than mDrawingState.
3901void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003902 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003903 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003904 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003905
3906 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3907}
3908
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003909void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003910{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003911 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003912
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003913 if (isLayerTripleBufferingDisabled())
3914 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003915
3916 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003917 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003918 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003919 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003920 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3921 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003922 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003923}
3924
Dan Stozab90cf072015-03-05 11:05:59 -08003925void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3926{
3927 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003928 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3929 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003930 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003931 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003932 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3933 b + 1, bucketTimeSec, percent);
3934 }
David Sodman4a36e932017-11-07 14:29:47 -08003935 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003936 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003937 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003938 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08003939 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003940}
3941
Dan Stozae77c7662016-05-13 11:37:28 -07003942void SurfaceFlinger::recordBufferingStats(const char* layerName,
3943 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08003944 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
3945 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07003946 for (const auto& segment : history) {
3947 if (!segment.usedThirdBuffer) {
3948 stats.twoBufferTime += segment.totalTime;
3949 }
3950 if (segment.occupancyAverage < 1.0f) {
3951 stats.doubleBufferedTime += segment.totalTime;
3952 } else if (segment.occupancyAverage < 2.0f) {
3953 stats.tripleBufferedTime += segment.totalTime;
3954 }
3955 ++stats.numSegments;
3956 stats.totalTime += segment.totalTime;
3957 }
3958}
3959
Brian Andersond6927fb2016-07-23 23:37:30 -07003960void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3961 result.appendFormat("Layer frame timestamps:\n");
3962
3963 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3964 const size_t count = currentLayers.size();
3965 for (size_t i=0 ; i<count ; i++) {
3966 currentLayers[i]->dumpFrameEvents(result);
3967 }
3968}
3969
Dan Stozae77c7662016-05-13 11:37:28 -07003970void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3971 result.append("Buffering stats:\n");
3972 result.append(" [Layer name] <Active time> <Two buffer> "
3973 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08003974 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07003975 typedef std::tuple<std::string, float, float, float> BufferTuple;
3976 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08003977 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07003978 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08003979 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07003980 if (stats.numSegments == 0) {
3981 continue;
3982 }
3983 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3984 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3985 stats.totalTime;
3986 float doubleBufferRatio = static_cast<float>(
3987 stats.doubleBufferedTime) / stats.totalTime;
3988 float tripleBufferRatio = static_cast<float>(
3989 stats.tripleBufferedTime) / stats.totalTime;
3990 sorted.insert({activeTime, {name, twoBufferRatio,
3991 doubleBufferRatio, tripleBufferRatio}});
3992 }
3993 for (const auto& sortedPair : sorted) {
3994 float activeTime = sortedPair.first;
3995 const BufferTuple& values = sortedPair.second;
3996 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3997 std::get<0>(values).c_str(), activeTime,
3998 std::get<1>(values), std::get<2>(values),
3999 std::get<3>(values));
4000 }
4001 result.append("\n");
4002}
4003
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004004void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4005 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Romain Guy54f154a2017-10-24 21:40:32 +01004006 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004007
4008 // TODO: print out if wide-color mode is active or not
4009
4010 for (size_t d = 0; d < mDisplays.size(); d++) {
4011 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4012 int32_t hwcId = displayDevice->getHwcDisplayId();
4013 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4014 continue;
4015 }
4016
4017 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004018 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004019 for (auto&& mode : modes) {
4020 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4021 }
4022
Peiyong Lina52f0292018-03-14 17:26:31 -07004023 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004024 result.appendFormat(" Current color mode: %s (%d)\n",
4025 decodeColorMode(currentMode).c_str(), currentMode);
4026 }
4027 result.append("\n");
4028}
4029
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004030LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004031 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004032 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4033 const State& state = useDrawing ? mDrawingState : mCurrentState;
4034 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004035 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004036 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004037 });
4038
4039 return layersProto;
4040}
4041
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004042LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4043 LayersProto layersProto;
4044
4045 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
4046 SizeProto* resolution = layersProto.mutable_resolution();
4047 resolution->set_w(displayDevice->getWidth());
4048 resolution->set_h(displayDevice->getHeight());
4049
4050 mDrawingState.traverseInZOrder([&](Layer* layer) {
4051 if (!layer->visibleRegion.isEmpty() &&
4052 layer->getBE().mHwcLayers.count(hwcId)) {
4053 LayerProto* layerProto = layersProto.add_layers();
4054 layer->writeToProto(layerProto, hwcId);
4055 }
4056 });
4057
4058 return layersProto;
4059}
4060
Mathias Agopian74d211a2013-04-22 16:55:35 +02004061void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4062 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004063{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004064 bool colorize = false;
4065 if (index < args.size()
4066 && (args[index] == String16("--color"))) {
4067 colorize = true;
4068 index++;
4069 }
4070
4071 Colorizer colorizer(colorize);
4072
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004073 // figure out if we're stuck somewhere
4074 const nsecs_t now = systemTime();
4075 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4076 const nsecs_t inTransaction(mDebugInTransaction);
4077 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4078 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4079
4080 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004081 * Dump library configuration.
4082 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004083
4084 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004085 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004086 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004087 appendSfConfigString(result);
4088 appendUiConfigString(result);
4089 appendGuiConfigString(result);
4090 result.append("\n");
4091
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004092 result.append("\nWide-Color information:\n");
4093 dumpWideColorInfo(result);
4094
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004095 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004096 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004097 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004098 result.append(SyncFeatures::getInstance().toString());
4099 result.append("\n");
4100
David Sodman105b7dc2017-11-04 20:28:14 -07004101 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004102
Andy McFadden41d67d72014-04-25 16:58:34 -07004103 colorizer.bold(result);
4104 result.append("DispSync configuration: ");
4105 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07004106 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004107 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08004108 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004109 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004110 result.append("\n");
4111
Dan Stozab90cf072015-03-05 11:05:59 -08004112 // Dump static screen stats
4113 result.append("\n");
4114 dumpStaticScreenStats(result);
4115 result.append("\n");
4116
Dan Stozae77c7662016-05-13 11:37:28 -07004117 dumpBufferingStats(result);
4118
Andy McFadden4803b742012-09-24 19:07:20 -07004119 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004120 * Dump the visible layer list
4121 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004122 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004123 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004124 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4125 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004126 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004127
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004128 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004129 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004130 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004131
4132 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004133 * Dump Display state
4134 */
4135
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004136 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004137 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004138 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004139 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4140 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004141 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004142 }
4143
4144 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004145 * Dump SurfaceFlinger global state
4146 */
4147
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004148 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004149 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004150 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004151
Mathias Agopian888c8222012-08-04 21:10:38 -07004152 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004153 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004154
David Sodmanbc815282017-11-05 18:57:52 -08004155 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004156
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004157 if (hw) {
4158 hw->undefinedRegion.dump(result, "undefinedRegion");
4159 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4160 hw->getOrientation(), hw->isDisplayOn());
4161 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004162 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004163 " last eglSwapBuffers() time: %f us\n"
4164 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004165 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004166 " refresh-rate : %f fps\n"
4167 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004168 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004169 " gpu_to_cpu_unsupported : %d\n"
4170 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004171 mLastSwapBufferTime/1000.0,
4172 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004173 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004174 1e9 / activeConfig->getVsyncPeriod(),
4175 activeConfig->getDpiX(),
4176 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004177 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004178
Mathias Agopian74d211a2013-04-22 16:55:35 +02004179 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004180 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004181
Mathias Agopian74d211a2013-04-22 16:55:35 +02004182 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004183 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004184
4185 /*
4186 * VSYNC state
4187 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004188 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004189 result.append("\n");
4190
4191 /*
4192 * HWC layer minidump
4193 */
4194 for (size_t d = 0; d < mDisplays.size(); d++) {
4195 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4196 int32_t hwcId = displayDevice->getHwcDisplayId();
4197 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4198 continue;
4199 }
4200
4201 result.appendFormat("Display %d HWC layers:\n", hwcId);
4202 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004203 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004204 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004205 });
Dan Stozae22aec72016-08-01 13:20:59 -07004206 result.append("\n");
4207 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004208
4209 /*
4210 * Dump HWComposer state
4211 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004212 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004213 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004214 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004215 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004216 result.appendFormat(" h/w composer %s\n",
4217 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004218 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004219
4220 /*
4221 * Dump gralloc state
4222 */
4223 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4224 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004225
4226 /*
4227 * Dump VrFlinger state if in use.
4228 */
4229 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4230 result.append("VrFlinger state:\n");
4231 result.append(mVrFlinger->Dump().c_str());
4232 result.append("\n");
4233 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004234}
4235
Mathias Agopian13127d82013-03-05 17:47:11 -08004236const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004237SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004238 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004239 wp<IBinder> dpy;
4240 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4241 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4242 dpy = mDisplays.keyAt(i);
4243 break;
4244 }
4245 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004246 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004247 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4248 // Just use the primary display so we have something to return
4249 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4250 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004251 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004252}
4253
Keun young Park63f165f2012-08-31 10:53:36 -07004254bool SurfaceFlinger::startDdmConnection()
4255{
4256 void* libddmconnection_dso =
4257 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4258 if (!libddmconnection_dso) {
4259 return false;
4260 }
4261 void (*DdmConnection_start)(const char* name);
4262 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004263 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004264 if (!DdmConnection_start) {
4265 dlclose(libddmconnection_dso);
4266 return false;
4267 }
4268 (*DdmConnection_start)(getServiceName());
4269 return true;
4270}
4271
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004272status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004273 switch (code) {
4274 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004275 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004276 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004277 case CLEAR_ANIMATION_FRAME_STATS:
4278 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004279 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004280 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004281 case ENABLE_VSYNC_INJECTIONS:
4282 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004283 {
4284 // codes that require permission check
4285 IPCThreadState* ipc = IPCThreadState::self();
4286 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004287 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004288 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004289 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004290 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004291 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004292 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004293 break;
4294 }
Robert Carr1db73f62016-12-21 12:58:51 -08004295 /*
4296 * Calling setTransactionState is safe, because you need to have been
4297 * granted a reference to Client* and Handle* to do anything with it.
4298 *
4299 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4300 */
4301 case SET_TRANSACTION_STATE:
4302 case CREATE_SCOPED_CONNECTION:
4303 {
4304 return OK;
4305 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004306 case CAPTURE_SCREEN:
4307 {
4308 // codes that require permission check
4309 IPCThreadState* ipc = IPCThreadState::self();
4310 const int pid = ipc->getCallingPid();
4311 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004312 if ((uid != AID_GRAPHICS) &&
4313 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004314 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004315 return PERMISSION_DENIED;
4316 }
4317 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004318 }
chaviwa76b2712017-09-20 12:02:26 -07004319 case CAPTURE_LAYERS: {
4320 IPCThreadState* ipc = IPCThreadState::self();
4321 const int pid = ipc->getCallingPid();
4322 const int uid = ipc->getCallingUid();
4323 if ((uid != AID_GRAPHICS) &&
4324 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4325 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4326 return PERMISSION_DENIED;
4327 }
4328 break;
4329 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004330 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004331 return OK;
4332}
4333
4334status_t SurfaceFlinger::onTransact(
4335 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4336{
4337 status_t credentialCheck = CheckTransactCodeCredentials(code);
4338 if (credentialCheck != OK) {
4339 return credentialCheck;
4340 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004341
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004342 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4343 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004344 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004345 IPCThreadState* ipc = IPCThreadState::self();
4346 const int uid = ipc->getCallingUid();
4347 if (CC_UNLIKELY(uid != AID_SYSTEM
4348 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004349 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004350 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004351 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004352 return PERMISSION_DENIED;
4353 }
4354 int n;
4355 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004356 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004357 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004358 return NO_ERROR;
4359 case 1002: // SHOW_UPDATES
4360 n = data.readInt32();
4361 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004362 invalidateHwcGeometry();
4363 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004364 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004365 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004366 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004367 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004368 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004369 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004370 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004371 setTransactionFlags(
4372 eTransactionNeeded|
4373 eDisplayTransactionNeeded|
4374 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004375 return NO_ERROR;
4376 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004377 case 1006:{ // send empty update
4378 signalRefresh();
4379 return NO_ERROR;
4380 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004381 case 1008: // toggle use of hw composer
4382 n = data.readInt32();
4383 mDebugDisableHWC = n ? 1 : 0;
4384 invalidateHwcGeometry();
4385 repaintEverything();
4386 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004387 case 1009: // toggle use of transform hint
4388 n = data.readInt32();
4389 mDebugDisableTransformHint = n ? 1 : 0;
4390 invalidateHwcGeometry();
4391 repaintEverything();
4392 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004393 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004394 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004395 reply->writeInt32(0);
4396 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004397 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004398 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004399 return NO_ERROR;
4400 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004401 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004402 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004403 return NO_ERROR;
4404 }
4405 case 1014: {
4406 // daltonize
4407 n = data.readInt32();
4408 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004409 case 1:
4410 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4411 break;
4412 case 2:
4413 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4414 break;
4415 case 3:
4416 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4417 break;
4418 default:
4419 mDaltonizer.setType(ColorBlindnessType::None);
4420 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004421 }
4422 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004423 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004424 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004425 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004426 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004427 invalidateHwcGeometry();
4428 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004429 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004430 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004431 case 1015: {
4432 // apply a color matrix
4433 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004434 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004435 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004436 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004437 for (size_t j = 0; j < 4; j++) {
4438 mColorMatrix[i][j] = data.readFloat();
4439 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004440 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004441 } else {
4442 mColorMatrix = mat4();
4443 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004444
4445 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4446 // the division by w in the fragment shader
4447 float4 lastRow(transpose(mColorMatrix)[3]);
4448 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4449 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4450 }
4451
Alan Viverette9c5a3332013-09-12 20:04:35 -07004452 invalidateHwcGeometry();
4453 repaintEverything();
4454 return NO_ERROR;
4455 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004456 // This is an experimental interface
4457 // Needs to be shifted to proper binder interface when we productize
4458 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004459 n = data.readInt32();
4460 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004461 return NO_ERROR;
4462 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004463 case 1017: {
4464 n = data.readInt32();
4465 mForceFullDamage = static_cast<bool>(n);
4466 return NO_ERROR;
4467 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004468 case 1018: { // Modify Choreographer's phase offset
4469 n = data.readInt32();
4470 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4471 return NO_ERROR;
4472 }
4473 case 1019: { // Modify SurfaceFlinger's phase offset
4474 n = data.readInt32();
4475 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4476 return NO_ERROR;
4477 }
Irvel468051e2016-06-13 16:44:44 -07004478 case 1020: { // Layer updates interceptor
4479 n = data.readInt32();
4480 if (n) {
4481 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004482 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004483 }
4484 else{
4485 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004486 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004487 }
4488 return NO_ERROR;
4489 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004490 case 1021: { // Disable HWC virtual displays
4491 n = data.readInt32();
4492 mUseHwcVirtualDisplays = !n;
4493 return NO_ERROR;
4494 }
Romain Guy0147a172017-06-01 13:53:56 -07004495 case 1022: { // Set saturation boost
4496 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4497
4498 invalidateHwcGeometry();
4499 repaintEverything();
4500 return NO_ERROR;
4501 }
Romain Guy54f154a2017-10-24 21:40:32 +01004502 case 1023: { // Set native mode
4503 mForceNativeColorMode = data.readInt32() == 1;
4504
4505 invalidateHwcGeometry();
4506 repaintEverything();
4507 return NO_ERROR;
4508 }
4509 case 1024: { // Is wide color gamut rendering/color management supported?
4510 reply->writeBool(hasWideColorDisplay);
4511 return NO_ERROR;
4512 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004513 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004514 n = data.readInt32();
4515 if (n) {
4516 ALOGV("LayerTracing enabled");
4517 mTracing.enable();
4518 doTracing("tracing.enable");
4519 reply->writeInt32(NO_ERROR);
4520 } else {
4521 ALOGV("LayerTracing disabled");
4522 status_t err = mTracing.disable();
4523 reply->writeInt32(err);
4524 }
4525 return NO_ERROR;
4526 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004527 case 1026: { // Get layer tracing status
4528 reply->writeBool(mTracing.isEnabled());
4529 return NO_ERROR;
4530 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004531 }
4532 }
4533 return err;
4534}
4535
Steven Thomas6d8110b2017-08-31 18:24:21 -07004536void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004537 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004538 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004539}
4540
Steven Thomas6d8110b2017-08-31 18:24:21 -07004541void SurfaceFlinger::repaintEverything() {
4542 ConditionalLock _l(mStateLock,
4543 std::this_thread::get_id() != mMainThreadId);
4544 repaintEverythingLocked();
4545}
4546
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004547// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4548class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004549public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004550 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4551 ~WindowDisconnector() {
4552 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004553 }
4554
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004555private:
4556 ANativeWindow* mWindow;
4557 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004558};
4559
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004560status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4561 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4562 int32_t minLayerZ, int32_t maxLayerZ,
4563 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004564 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004565 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004566
chaviwa76b2712017-09-20 12:02:26 -07004567 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4568
4569 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004570 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4571
chaviwa76b2712017-09-20 12:02:26 -07004572 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4573
4574 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4575 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004576 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004577}
4578
4579status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004580 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004581 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004582 ATRACE_CALL();
4583
4584 class LayerRenderArea : public RenderArea {
4585 public:
Robert Carr578038f2018-03-09 12:25:24 -08004586 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4587 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
4588 : RenderArea(reqHeight, reqWidth),
4589 mLayer(layer),
4590 mCrop(crop),
4591 mFlinger(flinger),
4592 mChildrenOnly(childrenOnly) {}
chaviwa76b2712017-09-20 12:02:26 -07004593 Rect getBounds() const override {
4594 const Layer::State& layerState(mLayer->getDrawingState());
4595 return Rect(layerState.active.w, layerState.active.h);
4596 }
4597 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4598 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4599 bool isSecure() const override { return false; }
4600 bool needsFiltering() const override { return false; }
Robert Carr578038f2018-03-09 12:25:24 -08004601 const Transform& getTransform() const { return mTransform; }
4602
4603 class ReparentForDrawing {
4604 public:
4605 const sp<Layer>& oldParent;
4606 const sp<Layer>& newParent;
4607
4608 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4609 : oldParent(oldParent), newParent(newParent) {
4610 oldParent->reparentChildrenForDrawing(newParent);
4611 }
4612 ~ReparentForDrawing() { newParent->reparentChildrenForDrawing(oldParent); }
4613 };
4614
4615 void render(std::function<void()> drawLayers) override {
4616 if (!mChildrenOnly) {
4617 mTransform = mLayer->getTransform().inverse();
4618 drawLayers();
4619 } else {
4620 Rect bounds = getBounds();
4621 screenshotParentLayer =
4622 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4623 bounds.getWidth(), bounds.getHeight(), 0);
4624
4625 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4626 drawLayers();
4627 }
4628 }
chaviwa76b2712017-09-20 12:02:26 -07004629
chaviw7206d492017-11-10 16:16:12 -08004630 Rect getSourceCrop() const override {
4631 if (mCrop.isEmpty()) {
4632 return getBounds();
4633 } else {
4634 return mCrop;
4635 }
4636 }
chaviwa76b2712017-09-20 12:02:26 -07004637 bool getWideColorSupport() const override { return false; }
Peiyong Lina52f0292018-03-14 17:26:31 -07004638 ColorMode getActiveColorMode() const override { return ColorMode::NATIVE; }
chaviwa76b2712017-09-20 12:02:26 -07004639
4640 private:
chaviw7206d492017-11-10 16:16:12 -08004641 const sp<Layer> mLayer;
4642 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004643
4644 // In the "childrenOnly" case we reparent the children to a screenshot
4645 // layer which has no properties set and which does not draw.
4646 sp<ContainerLayer> screenshotParentLayer;
4647 Transform mTransform;
4648
4649 SurfaceFlinger* mFlinger;
4650 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004651 };
4652
4653 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4654 auto parent = layerHandle->owner.promote();
4655
chaviw7206d492017-11-10 16:16:12 -08004656 if (parent == nullptr || parent->isPendingRemoval()) {
4657 ALOGE("captureLayers called with a removed parent");
4658 return NAME_NOT_FOUND;
4659 }
4660
Robert Carr578038f2018-03-09 12:25:24 -08004661 const int uid = IPCThreadState::self()->getCallingUid();
4662 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4663 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4664 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4665 return PERMISSION_DENIED;
4666 }
4667
chaviw7206d492017-11-10 16:16:12 -08004668 Rect crop(sourceCrop);
4669 if (sourceCrop.width() <= 0) {
4670 crop.left = 0;
4671 crop.right = parent->getCurrentState().active.w;
4672 }
4673
4674 if (sourceCrop.height() <= 0) {
4675 crop.top = 0;
4676 crop.bottom = parent->getCurrentState().active.h;
4677 }
4678
4679 int32_t reqWidth = crop.width() * frameScale;
4680 int32_t reqHeight = crop.height() * frameScale;
4681
Robert Carr578038f2018-03-09 12:25:24 -08004682 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004683
Robert Carr578038f2018-03-09 12:25:24 -08004684 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004685 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4686 if (!layer->isVisible()) {
4687 return;
Robert Carr578038f2018-03-09 12:25:24 -08004688 } else if (childrenOnly && layer == parent.get()) {
4689 return;
chaviwa76b2712017-09-20 12:02:26 -07004690 }
4691 visitor(layer);
4692 });
4693 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004694 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004695}
4696
4697status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4698 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004699 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004700 bool useIdentityTransform) {
4701 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004702
chaviwa76b2712017-09-20 12:02:26 -07004703 renderArea.updateDimensions();
4704
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004705 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4706 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4707 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4708 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004709
4710 // This mutex protects syncFd and captureResult for communication of the return values from the
4711 // main thread back to this Binder thread
4712 std::mutex captureMutex;
4713 std::condition_variable captureCondition;
4714 std::unique_lock<std::mutex> captureLock(captureMutex);
4715 int syncFd = -1;
4716 std::optional<status_t> captureResult;
4717
Robert Carr03480e22018-01-04 16:02:06 -08004718 const int uid = IPCThreadState::self()->getCallingUid();
4719 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4720
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004721 sp<LambdaMessage> message = new LambdaMessage([&]() {
4722 // If there is a refresh pending, bug out early and tell the binder thread to try again
4723 // after the refresh.
4724 if (mRefreshPending) {
4725 ATRACE_NAME("Skipping screenshot for now");
4726 std::unique_lock<std::mutex> captureLock(captureMutex);
4727 captureResult = std::make_optional<status_t>(EAGAIN);
4728 captureCondition.notify_one();
4729 return;
4730 }
4731
4732 status_t result = NO_ERROR;
4733 int fd = -1;
4734 {
4735 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004736 renderArea.render([&]() {
4737 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4738 useIdentityTransform, forSystem, &fd);
4739 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004740 }
4741
4742 {
4743 std::unique_lock<std::mutex> captureLock(captureMutex);
4744 syncFd = fd;
4745 captureResult = std::make_optional<status_t>(result);
4746 captureCondition.notify_one();
4747 }
4748 });
4749
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004750 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004751 if (result == NO_ERROR) {
4752 captureCondition.wait(captureLock, [&]() { return captureResult; });
4753 while (*captureResult == EAGAIN) {
4754 captureResult.reset();
4755 result = postMessageAsync(message);
4756 if (result != NO_ERROR) {
4757 return result;
4758 }
4759 captureCondition.wait(captureLock, [&]() { return captureResult; });
4760 }
4761 result = *captureResult;
4762 }
4763
4764 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004765 sync_wait(syncFd, -1);
4766 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004767 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004768
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004769 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004770}
4771
chaviwa76b2712017-09-20 12:02:26 -07004772void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4773 TraverseLayersFunction traverseLayers, bool yswap,
4774 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004775 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004776
Lloyd Pique144e1162017-12-20 16:44:52 -08004777 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004778
4779 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004780 const auto raWidth = renderArea.getWidth();
4781 const auto raHeight = renderArea.getHeight();
4782
4783 const auto reqWidth = renderArea.getReqWidth();
4784 const auto reqHeight = renderArea.getReqHeight();
4785 Rect sourceCrop = renderArea.getSourceCrop();
4786
4787 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4788 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004789
Dan Stozac1879002014-05-22 15:59:05 -07004790 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004791 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004792 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004793 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004794 }
4795
4796 // ensure that sourceCrop is inside screen
4797 if (sourceCrop.left < 0) {
4798 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4799 }
chaviwa76b2712017-09-20 12:02:26 -07004800 if (sourceCrop.right > raWidth) {
4801 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004802 }
4803 if (sourceCrop.top < 0) {
4804 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4805 }
chaviwa76b2712017-09-20 12:02:26 -07004806 if (sourceCrop.bottom > raHeight) {
4807 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004808 }
4809
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004810 android_dataspace outputDataspace = HAL_DATASPACE_UNKNOWN;
Chia-I Wu9a48a8c2018-02-20 14:27:30 -08004811 if (renderArea.getWideColorSupport() &&
Peiyong Lina52f0292018-03-14 17:26:31 -07004812 renderArea.getActiveColorMode() == ColorMode::DISPLAY_P3) {
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004813 outputDataspace = HAL_DATASPACE_DISPLAY_P3;
4814 }
4815 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Romain Guy88d37dd2017-05-26 17:57:05 -07004816
Mathias Agopian180f10d2013-04-10 22:55:41 -07004817 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004818 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004819
4820 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004821 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4822 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004823 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004824
4825 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004826 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004827
chaviwa76b2712017-09-20 12:02:26 -07004828 traverseLayers([&](Layer* layer) {
4829 if (filtering) layer->setFiltering(true);
David Sodmandc5e0622018-01-05 23:10:57 -08004830 layer->drawNow(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004831 if (filtering) layer->setFiltering(false);
4832 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004833}
4834
chaviwa76b2712017-09-20 12:02:26 -07004835status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4836 TraverseLayersFunction traverseLayers,
4837 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004838 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08004839 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07004840 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004841 ATRACE_CALL();
4842
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004843 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004844
4845 traverseLayers([&](Layer* layer) {
4846 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4847 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004848
Robert Carr03480e22018-01-04 16:02:06 -08004849 // We allow the system server to take screenshots of secure layers for
4850 // use in situations like the Screen-rotation animation and place
4851 // the impetus on WindowManager to not persist them.
4852 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004853 ALOGW("FB is protected: PERMISSION_DENIED");
4854 return PERMISSION_DENIED;
4855 }
4856
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004857 // this binds the given EGLImage as a framebuffer for the
4858 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08004859 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08004860 if (bufferBond.getStatus() != NO_ERROR) {
4861 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004862 return INVALID_OPERATION;
4863 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004864
Dan Stozaabcda352017-06-01 14:37:39 -07004865 // this will in fact render into our dequeued buffer
4866 // via an FBO, which means we didn't have to create
4867 // an EGLSurface and therefore we're not
4868 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004869 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004870
Dan Stozaabcda352017-06-01 14:37:39 -07004871 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08004872 getRenderEngine().finish();
4873 *outSyncFd = -1;
4874
chaviwa76b2712017-09-20 12:02:26 -07004875 const auto reqWidth = renderArea.getReqWidth();
4876 const auto reqHeight = renderArea.getReqHeight();
4877
Dan Stozaabcda352017-06-01 14:37:39 -07004878 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4879 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004880 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004881 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08004882 } else {
4883 base::unique_fd syncFd = getRenderEngine().flush();
4884 if (syncFd < 0) {
4885 getRenderEngine().finish();
4886 }
4887 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07004888 }
4889
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004890 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004891}
4892
Mathias Agopiand5556842013-09-19 17:08:37 -07004893void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07004894 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004895 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004896 for (size_t y = 0; y < h; y++) {
4897 uint32_t const* p = (uint32_t const*)vaddr + y * s;
4898 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004899 if (p[x] != 0xFF000000) return;
4900 }
4901 }
chaviwa76b2712017-09-20 12:02:26 -07004902 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07004903
Robert Carr2047fae2016-11-28 14:09:09 -08004904 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07004905 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004906 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07004907 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4908 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
4909 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
4910 static_cast<float>(state.color.a));
4911 i++;
4912 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07004913 }
4914}
4915
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004916// ---------------------------------------------------------------------------
4917
Dan Stoza412903f2017-04-27 13:42:17 -07004918void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4919 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004920}
4921
Dan Stoza412903f2017-04-27 13:42:17 -07004922void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4923 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004924}
4925
chaviwa76b2712017-09-20 12:02:26 -07004926void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
4927 int32_t maxLayerZ,
4928 const LayerVector::Visitor& visitor) {
4929 // We loop through the first level of layers without traversing,
4930 // as we need to interpret min/max layer Z in the top level Z space.
4931 for (const auto& layer : mDrawingState.layersSortedByZ) {
4932 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4933 continue;
4934 }
4935 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08004936 // relative layers are traversed in Layer::traverseInZOrder
4937 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07004938 continue;
4939 }
4940 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01004941 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4942 return;
4943 }
chaviwa76b2712017-09-20 12:02:26 -07004944 if (!layer->isVisible()) {
4945 return;
4946 }
4947 visitor(layer);
4948 });
4949 }
4950}
4951
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004952}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004953
Mathias Agopian3f844832013-08-07 21:24:32 -07004954#if defined(__gl_h_)
4955#error "don't include gl/gl.h in this file"
4956#endif
4957
4958#if defined(__gl2_h_)
4959#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08004960#endif