blob: 5c69b98b98b6b4c4017cc94866af07eb94569644 [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 Pique09594832018-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 Pique2d3ee6d2018-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 Pique09594832018-01-22 17:48:03 -0800223 mCreateBufferQueue(&BufferQueue::createBufferQueue),
224 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Pique2d3ee6d2018-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 Pique9123ae52018-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 Pique4d234852018-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 Pique4d234852018-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 Pique9123ae52018-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 Pique9123ae52018-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 Pique0c3a8832018-01-22 17:31:47 -0800669 mEventControlThread = std::make_unique<impl::EventControlThread>(
670 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700671
Mathias Agopian92a979a2012-08-02 18:32:23 -0700672 // initialize our drawing state
673 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700674
Andy McFadden13a082e2012-08-24 10:16:42 -0700675 // set initial conditions (e.g. unblank default device)
676 initializeDisplays();
677
David Sodmanbc815282017-11-05 18:57:52 -0800678 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700679
Wei Wangf9b05ee2017-07-19 20:59:39 -0700680 // Inform native graphics APIs whether the present timestamp is supported:
681 if (getHwComposer().hasCapability(
682 HWC2::Capability::PresentFenceIsNotReliable)) {
683 mStartPropertySetThread = new StartPropertySetThread(false);
684 } else {
685 mStartPropertySetThread = new StartPropertySetThread(true);
686 }
687
688 if (mStartPropertySetThread->Start() != NO_ERROR) {
689 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800690 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800691
Dan Stoza9e56aa02015-11-02 13:00:03 -0800692 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700693}
694
Romain Guy11d63f42017-07-20 12:47:14 -0700695void SurfaceFlinger::readPersistentProperties() {
696 char value[PROPERTY_VALUE_MAX];
697
698 property_get("persist.sys.sf.color_saturation", value, "1.0");
699 mSaturation = atof(value);
700 ALOGV("Saturation is set to %.2f", mSaturation);
Romain Guy54f154a2017-10-24 21:40:32 +0100701
702 property_get("persist.sys.sf.native_mode", value, "0");
703 mForceNativeColorMode = atoi(value) == 1;
704 if (mForceNativeColorMode) {
705 ALOGV("Forcing native color mode");
706 }
Romain Guy11d63f42017-07-20 12:47:14 -0700707}
708
Mathias Agopiana67e4182012-06-19 17:26:12 -0700709void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800710 // Start boot animation service by setting a property mailbox
711 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700712 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800713 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700714 if (mStartPropertySetThread->join() != NO_ERROR) {
715 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800716 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700717}
718
Mathias Agopian875d8e12013-06-07 15:35:48 -0700719size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800720 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700721}
722
Mathias Agopian875d8e12013-06-07 15:35:48 -0700723size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800724 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700725}
726
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800727// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800728
Jamie Gennis582270d2011-08-17 18:19:00 -0700729bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800730 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800731 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800732 return authenticateSurfaceTextureLocked(bufferProducer);
733}
734
735bool SurfaceFlinger::authenticateSurfaceTextureLocked(
736 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800737 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800738 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800739}
740
Brian Anderson6b376712017-04-04 10:51:39 -0700741status_t SurfaceFlinger::getSupportedFrameTimestamps(
742 std::vector<FrameEvent>* outSupported) const {
743 *outSupported = {
744 FrameEvent::REQUESTED_PRESENT,
745 FrameEvent::ACQUIRE,
746 FrameEvent::LATCH,
747 FrameEvent::FIRST_REFRESH_START,
748 FrameEvent::LAST_REFRESH_START,
749 FrameEvent::GPU_COMPOSITION_DONE,
750 FrameEvent::DEQUEUE_READY,
751 FrameEvent::RELEASE,
752 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700753 ConditionalLock _l(mStateLock,
754 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700755 if (!getHwComposer().hasCapability(
756 HWC2::Capability::PresentFenceIsNotReliable)) {
757 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
758 }
759 return NO_ERROR;
760}
761
Dan Stoza7f7da322014-05-02 15:26:25 -0700762status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
763 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800764 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700765 return BAD_VALUE;
766 }
767
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500768 if (!display.get())
769 return NAME_NOT_FOUND;
770
Jesse Hall692c7232012-11-08 15:41:56 -0800771 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700772 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800773 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700774 type = i;
775 break;
776 }
777 }
778
779 if (type < 0) {
780 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700781 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700782
Mathias Agopian8b736f12012-08-13 17:54:26 -0700783 // TODO: Not sure if display density should handled by SF any longer
784 class Density {
785 static int getDensityFromProperty(char const* propName) {
786 char property[PROPERTY_VALUE_MAX];
787 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800788 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700789 density = atoi(property);
790 }
791 return density;
792 }
793 public:
794 static int getEmuDensity() {
795 return getDensityFromProperty("qemu.sf.lcd_density"); }
796 static int getBuildDensity() {
797 return getDensityFromProperty("ro.sf.lcd_density"); }
798 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700799
Dan Stoza7f7da322014-05-02 15:26:25 -0700800 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700801
Steven Thomas6d8110b2017-08-31 18:24:21 -0700802 ConditionalLock _l(mStateLock,
803 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800804 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700805 DisplayInfo info = DisplayInfo();
806
Dan Stoza9e56aa02015-11-02 13:00:03 -0800807 float xdpi = hwConfig->getDpiX();
808 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700809
810 if (type == DisplayDevice::DISPLAY_PRIMARY) {
811 // The density of the device is provided by a build property
812 float density = Density::getBuildDensity() / 160.0f;
813 if (density == 0) {
814 // the build doesn't provide a density -- this is wrong!
815 // use xdpi instead
816 ALOGE("ro.sf.lcd_density must be defined as a build property");
817 density = xdpi / 160.0f;
818 }
819 if (Density::getEmuDensity()) {
820 // if "qemu.sf.lcd_density" is specified, it overrides everything
821 xdpi = ydpi = density = Density::getEmuDensity();
822 density /= 160.0f;
823 }
824 info.density = density;
825
826 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700827 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800828 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700829 } else {
830 // TODO: where should this value come from?
831 static const int TV_DENSITY = 213;
832 info.density = TV_DENSITY / 160.0f;
833 info.orientation = 0;
834 }
835
Dan Stoza9e56aa02015-11-02 13:00:03 -0800836 info.w = hwConfig->getWidth();
837 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700838 info.xdpi = xdpi;
839 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800840 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900841 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800842
Andy McFadden91b2ca82014-06-13 14:04:23 -0700843 // This is how far in advance a buffer must be queued for
844 // presentation at a given time. If you want a buffer to appear
845 // on the screen at time N, you must submit the buffer before
846 // (N - presentationDeadline).
847 //
848 // Normally it's one full refresh period (to give SF a chance to
849 // latch the buffer), but this can be reduced by configuring a
850 // DispSync offset. Any additional delays introduced by the hardware
851 // composer or panel must be accounted for here.
852 //
853 // We add an additional 1ms to allow for processing time and
854 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800855 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800856 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700857
858 // All non-virtual displays are currently considered secure.
859 info.secure = true;
860
Michael Wright28f24d02016-07-12 13:30:53 -0700861 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700862 }
863
Dan Stoza7f7da322014-05-02 15:26:25 -0700864 return NO_ERROR;
865}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700866
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800867status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700868 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800869 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700870 return BAD_VALUE;
871 }
872
873 // FIXME for now we always return stats for the primary display
874 memset(stats, 0, sizeof(*stats));
875 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
876 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
877 return NO_ERROR;
878}
879
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700880int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800881 if (display == nullptr) {
882 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800883 return BAD_VALUE;
884 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700885
886 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800887 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700888 return device->getActiveConfig();
889 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700890
Dan Stoza24a42e92015-03-09 10:04:11 -0700891 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700892}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700893
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700894void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
895 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
896 this);
897 int32_t type = hw->getDisplayType();
898 int currentMode = hw->getActiveConfig();
899
900 if (mode == currentMode) {
901 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
902 return;
903 }
904
905 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
906 ALOGW("Trying to set config for virtual display");
907 return;
908 }
909
910 hw->setActiveConfig(mode);
911 getHwComposer().setActiveConfig(type, mode);
912}
913
914status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
915 class MessageSetActiveConfig: public MessageBase {
916 SurfaceFlinger& mFlinger;
917 sp<IBinder> mDisplay;
918 int mMode;
919 public:
920 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
921 int mode) :
922 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
923 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700924 Vector<DisplayInfo> configs;
925 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700926 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700927 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700928 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700929 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700930 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700931 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800932 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700933 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700934 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700935 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
936 ALOGW("Attempt to set active config = %d for virtual display",
937 mMode);
938 } else {
939 mFlinger.setActiveConfigInternal(hw, mMode);
940 }
941 return true;
942 }
943 };
944 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
945 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700946 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700947}
Michael Wright28f24d02016-07-12 13:30:53 -0700948status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -0700949 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700950 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
951 return BAD_VALUE;
952 }
953
954 if (!display.get()) {
955 return NAME_NOT_FOUND;
956 }
957
958 int32_t type = NAME_NOT_FOUND;
959 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
960 if (display == mBuiltinDisplays[i]) {
961 type = i;
962 break;
963 }
964 }
965
966 if (type < 0) {
967 return type;
968 }
969
Peiyong Lina52f0292018-03-14 17:26:31 -0700970 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700971 {
972 ConditionalLock _l(mStateLock,
973 std::this_thread::get_id() != mMainThreadId);
974 modes = getHwComposer().getColorModes(type);
975 }
Michael Wright28f24d02016-07-12 13:30:53 -0700976 outColorModes->clear();
977 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
978
979 return NO_ERROR;
980}
981
Peiyong Lina52f0292018-03-14 17:26:31 -0700982ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700983 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700984 if (device != nullptr) {
985 return device->getActiveColorMode();
986 }
Peiyong Lina52f0292018-03-14 17:26:31 -0700987 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -0700988}
989
990void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lina52f0292018-03-14 17:26:31 -0700991 ColorMode mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700992 int32_t type = hw->getDisplayType();
Peiyong Lina52f0292018-03-14 17:26:31 -0700993 ColorMode currentMode = hw->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -0700994
995 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700996 return;
997 }
998
999 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1000 ALOGW("Trying to set config for virtual display");
1001 return;
1002 }
1003
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001004 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
1005 hw->getDisplayType());
1006
Michael Wright28f24d02016-07-12 13:30:53 -07001007 hw->setActiveColorMode(mode);
1008 getHwComposer().setActiveColorMode(type, mode);
1009}
1010
1011
1012status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001013 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -07001014 class MessageSetActiveColorMode: public MessageBase {
1015 SurfaceFlinger& mFlinger;
1016 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -07001017 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001018 public:
1019 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -07001020 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -07001021 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1022 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -07001023 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001024 mFlinger.getDisplayColorModes(mDisplay, &modes);
1025 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -07001026 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001027 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1028 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001029 return true;
1030 }
1031 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1032 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001033 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1034 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001035 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001036 ALOGW("Attempt to set active color mode %s %d for virtual display",
1037 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001038 } else {
1039 mFlinger.setActiveColorModeInternal(hw, mMode);
1040 }
1041 return true;
1042 }
1043 };
1044 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1045 postMessageSync(msg);
1046 return NO_ERROR;
1047}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001048
Svetoslavd85084b2014-03-20 10:28:31 -07001049status_t SurfaceFlinger::clearAnimationFrameStats() {
1050 Mutex::Autolock _l(mStateLock);
1051 mAnimFrameTracker.clearStats();
1052 return NO_ERROR;
1053}
1054
1055status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1056 Mutex::Autolock _l(mStateLock);
1057 mAnimFrameTracker.getStats(outStats);
1058 return NO_ERROR;
1059}
1060
Dan Stozac4f471e2016-03-24 09:31:08 -07001061status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1062 HdrCapabilities* outCapabilities) const {
1063 Mutex::Autolock _l(mStateLock);
1064
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001065 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001066 if (displayDevice == nullptr) {
1067 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1068 return BAD_VALUE;
1069 }
1070
1071 std::unique_ptr<HdrCapabilities> capabilities =
David Sodman105b7dc2017-11-04 20:28:14 -07001072 getBE().mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
Dan Stozac4f471e2016-03-24 09:31:08 -07001073 if (capabilities) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001074 if (displayDevice->getWideColorSupport() && !displayDevice->getHdrSupport()) {
1075 // insert HDR10 as we will force client composition for HDR10
1076 // layers
1077 std::vector<int32_t> types = capabilities->getSupportedHdrTypes();
1078 types.push_back(HAL_HDR_HDR10);
1079
1080 *outCapabilities = HdrCapabilities(types,
1081 capabilities->getDesiredMaxLuminance(),
1082 capabilities->getDesiredMaxAverageLuminance(),
1083 capabilities->getDesiredMinLuminance());
1084 } else {
1085 *outCapabilities = std::move(*capabilities);
1086 }
Dan Stozac4f471e2016-03-24 09:31:08 -07001087 } else {
1088 return BAD_VALUE;
1089 }
1090
1091 return NO_ERROR;
1092}
1093
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001094status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001095 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1096 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001097
Chia-I Wu90f669f2017-10-05 14:24:41 -07001098 if (mInjectVSyncs == enable) {
1099 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001100 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001101
1102 if (enable) {
1103 ALOGV("VSync Injections enabled");
1104 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001105 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique0fcde1b2017-12-20 16:50:21 -08001106 mInjectorEventThread =
1107 std::make_unique<impl::EventThread>(mVSyncInjector.get(), *this, false,
1108 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001109 }
Lloyd Pique9123ae52018-01-22 17:14:00 -08001110 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001111 } else {
1112 ALOGV("VSync Injections disabled");
Lloyd Pique9123ae52018-01-22 17:14:00 -08001113 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001114 }
1115
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001116 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001117 });
1118 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001119 return NO_ERROR;
1120}
1121
1122status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001123 Mutex::Autolock _l(mStateLock);
1124
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001125 if (!mInjectVSyncs) {
1126 ALOGE("VSync Injections not enabled");
1127 return BAD_VALUE;
1128 }
1129 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1130 ALOGV("Injecting VSync inside SurfaceFlinger");
1131 mVSyncInjector->onInjectSyncEvent(when);
1132 }
1133 return NO_ERROR;
1134}
1135
Lloyd Pique755e3192018-01-31 16:46:15 -08001136status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1137 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001138 IPCThreadState* ipc = IPCThreadState::self();
1139 const int pid = ipc->getCallingPid();
1140 const int uid = ipc->getCallingUid();
1141 if ((uid != AID_SHELL) &&
1142 !PermissionCache::checkPermission(sDump, pid, uid)) {
1143 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1144 return PERMISSION_DENIED;
1145 }
1146
1147 // Try to acquire a lock for 1s, fail gracefully
1148 const status_t err = mStateLock.timedLock(s2ns(1));
1149 const bool locked = (err == NO_ERROR);
1150 if (!locked) {
1151 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1152 return TIMED_OUT;
1153 }
1154
1155 outLayers->clear();
1156 mCurrentState.traverseInZOrder([&](Layer* layer) {
1157 outLayers->push_back(layer->getLayerDebugInfo());
1158 });
1159
1160 mStateLock.unlock();
1161 return NO_ERROR;
1162}
1163
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001164// ----------------------------------------------------------------------------
1165
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001166sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1167 ISurfaceComposer::VsyncSource vsyncSource) {
1168 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1169 return mSFEventThread->createEventConnection();
1170 } else {
1171 return mEventThread->createEventConnection();
1172 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001173}
1174
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001175// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001176
1177void SurfaceFlinger::waitForEvent() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001178 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001179}
1180
1181void SurfaceFlinger::signalTransaction() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001182 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001183}
1184
1185void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001186 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001187}
1188
1189void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001190 mRefreshPending = true;
Lloyd Pique9123ae52018-01-22 17:14:00 -08001191 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001192}
1193
1194status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001195 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001196 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001197}
1198
1199status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001200 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001201 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001202 if (res == NO_ERROR) {
1203 msg->wait();
1204 }
1205 return res;
1206}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001207
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001208void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001209 do {
1210 waitForEvent();
1211 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001212}
1213
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001214void SurfaceFlinger::enableHardwareVsync() {
1215 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001216 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001217 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001218 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1219 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001220 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001221 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001222}
1223
Jesse Hall948fe0c2013-10-14 12:56:09 -07001224void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001225 Mutex::Autolock _l(mHWVsyncLock);
1226
Jesse Hall948fe0c2013-10-14 12:56:09 -07001227 if (makeAvailable) {
1228 mHWVsyncAvailable = true;
1229 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001230 // Hardware vsync is not currently available, so abort the resync
1231 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001232 return;
1233 }
1234
David Sodman105b7dc2017-11-04 20:28:14 -07001235 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001236 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001237
1238 mPrimaryDispSync.reset();
1239 mPrimaryDispSync.setPeriod(period);
1240
1241 if (!mPrimaryHWVsyncEnabled) {
1242 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001243 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1244 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001245 mPrimaryHWVsyncEnabled = true;
1246 }
1247}
1248
Jesse Hall948fe0c2013-10-14 12:56:09 -07001249void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001250 Mutex::Autolock _l(mHWVsyncLock);
1251 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001252 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1253 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001254 mPrimaryDispSync.endResync();
1255 mPrimaryHWVsyncEnabled = false;
1256 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001257 if (makeUnavailable) {
1258 mHWVsyncAvailable = false;
1259 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001260}
1261
Tim Murray4a4e4a22016-04-19 16:29:23 +00001262void SurfaceFlinger::resyncWithRateLimit() {
1263 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001264
1265 // No explicit locking is needed here since EventThread holds a lock while calling this method
1266 static nsecs_t sLastResyncAttempted = 0;
1267 const nsecs_t now = systemTime();
1268 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001269 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001270 }
Dan Stoza57164302017-05-08 14:03:54 -07001271 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001272}
1273
Steven Thomasb02664d2017-07-26 18:48:28 -07001274void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1275 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001276 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001277 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001278 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001279 return;
1280 }
1281
1282 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001283 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001284 return;
1285 }
1286
Jamie Gennisd1700752013-10-14 12:22:52 -07001287 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001288
Jamie Gennisd1700752013-10-14 12:22:52 -07001289 { // Scope for the lock
1290 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001291 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001292 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001293 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001294 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001295
1296 if (needsHwVsync) {
1297 enableHardwareVsync();
1298 } else {
1299 disableHardwareVsync(false);
1300 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001301}
1302
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001303void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001304 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1305 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001306}
1307
Lloyd Pique715a2c12017-12-14 17:18:08 -08001308void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1309 HWC2::Connection connection) {
1310 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1311 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001312
Lloyd Piqueba04e622017-12-14 17:11:26 -08001313 // Ignore events that do not have the right sequenceId.
1314 if (sequenceId != getBE().mComposerSequenceId) {
1315 return;
1316 }
1317
Steven Thomasb02664d2017-07-26 18:48:28 -07001318 // Only lock if we're not on the main thread. This function is normally
1319 // called on a hwbinder thread, but for the primary display it's called on
1320 // the main thread with the state lock already held, so don't attempt to
1321 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001322 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001323
Lloyd Pique715a2c12017-12-14 17:18:08 -08001324 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001325
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001326 if (std::this_thread::get_id() == mMainThreadId) {
1327 // Process all pending hot plug events immediately if we are on the main thread.
1328 processDisplayHotplugEventsLocked();
1329 }
1330
Lloyd Piqueba04e622017-12-14 17:11:26 -08001331 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001332}
1333
Steven Thomasb02664d2017-07-26 18:48:28 -07001334void SurfaceFlinger::onRefreshReceived(int sequenceId,
1335 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001336 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001337 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001338 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001339 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001340 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001341}
1342
Dan Stoza9e56aa02015-11-02 13:00:03 -08001343void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001344 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001345 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001346 getHwComposer().setVsyncEnabled(disp,
1347 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001348}
1349
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001350// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001351void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001352 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001353 // Clear the drawing state so that the logic inside of
1354 // handleTransactionLocked will fire. It will determine the delta between
1355 // mCurrentState and mDrawingState and re-apply all changes when we make the
1356 // transition.
1357 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001358 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001359 mDisplays.clear();
1360}
1361
Steven Thomas050b2c82017-03-06 11:45:16 -08001362void SurfaceFlinger::updateVrFlinger() {
1363 if (!mVrFlinger)
1364 return;
1365 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001366 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001367 return;
1368 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001369
David Sodman105b7dc2017-11-04 20:28:14 -07001370 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001371 ALOGE("Vr flinger is only supported for remote hardware composer"
1372 " service connections. Ignoring request to transition to vr"
1373 " flinger.");
1374 mVrFlingerRequestsDisplay = false;
1375 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001376 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001377
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001378 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001379
Steven Thomasb02664d2017-07-26 18:48:28 -07001380 int currentDisplayPowerMode = getDisplayDeviceLocked(
1381 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001382
Steven Thomasb02664d2017-07-26 18:48:28 -07001383 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001384 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001385 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001386
Steven Thomasb02664d2017-07-26 18:48:28 -07001387 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001388 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001389 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1390 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001391 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001392
David Sodman105b7dc2017-11-04 20:28:14 -07001393 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1394 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001395
1396 if (vrFlingerRequestsDisplay) {
1397 mVrFlinger->GrantDisplayOwnership();
1398 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001399 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001400 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001401
1402 mVisibleRegionsDirty = true;
1403 invalidateHwcGeometry();
1404
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001405 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001406 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1407 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1408 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001409
Steven Thomasb02664d2017-07-26 18:48:28 -07001410 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001411 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001412 const nsecs_t period = activeConfig->getVsyncPeriod();
1413 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001414
Steven Thomasb02664d2017-07-26 18:48:28 -07001415 // Use phase of 0 since phase is not known.
1416 // Use latency of 0, which will snap to the ideal latency.
1417 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001418
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001419 android_atomic_or(1, &mRepaintEverything);
1420 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001421}
1422
Mathias Agopian4fec8732012-06-29 14:12:52 -07001423void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001424 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001425 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001426 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001427 bool frameMissed = !mHadClientComposition &&
1428 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001429 (mPreviousPresentFence->getSignalTime() ==
1430 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001431 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001432 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001433 signalLayerUpdate();
1434 break;
1435 }
1436
Steven Thomas050b2c82017-03-06 11:45:16 -08001437 // Now that we're going to make it to the handleMessageTransaction()
1438 // call below it's safe to call updateVrFlinger(), which will
1439 // potentially trigger a display handoff.
1440 updateVrFlinger();
1441
Dan Stoza6b9454d2014-11-07 16:00:59 -08001442 bool refreshNeeded = handleMessageTransaction();
1443 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001444 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001445 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001446 // Signal a refresh if a transaction modified the window state,
1447 // a new buffer was latched, or if HWC has requested a full
1448 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001449 signalRefresh();
1450 }
1451 break;
1452 }
1453 case MessageQueue::REFRESH: {
1454 handleMessageRefresh();
1455 break;
1456 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001457 }
1458}
1459
Dan Stoza6b9454d2014-11-07 16:00:59 -08001460bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001461 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001462 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001463 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001464 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001465 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001466 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001467}
1468
Dan Stoza6b9454d2014-11-07 16:00:59 -08001469bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001470 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001471 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001472}
1473
1474void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001475 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001476
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001477 mRefreshPending = false;
1478
Pablo Ceballos40845df2016-01-25 17:41:15 -08001479 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001480
Brian Andersond6927fb2016-07-23 23:37:30 -07001481 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001482 rebuildLayerStacks();
1483 setUpHWComposer();
1484 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001485 doTracing("handleRefresh");
Dan Stoza05dacfb2016-07-01 13:33:38 -07001486 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001487 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001488
David Sodman105b7dc2017-11-04 20:28:14 -07001489 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001490
1491 mHadClientComposition = false;
1492 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1493 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1494 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001495 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001496 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001497
Dan Stoza9e56aa02015-11-02 13:00:03 -08001498 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001499}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001500
Mathias Agopiancd60f992012-08-16 16:28:27 -07001501void SurfaceFlinger::doDebugFlashRegions()
1502{
1503 // is debugging enabled
1504 if (CC_LIKELY(!mDebugRegion))
1505 return;
1506
1507 const bool repaintEverything = mRepaintEverything;
1508 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1509 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001510 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001511 // transform the dirty region into this screen's coordinate space
1512 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1513 if (!dirtyRegion.isEmpty()) {
1514 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001515 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001516
1517 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001518 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001519 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001520 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1521
Mathias Agopianda27af92012-09-13 18:17:13 -07001522 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001523 }
1524 }
1525 }
1526
1527 postFramebuffer();
1528
1529 if (mDebugRegion > 1) {
1530 usleep(mDebugRegion * 1000);
1531 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001532
Dan Stoza9e56aa02015-11-02 13:00:03 -08001533 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001534 auto& displayDevice = mDisplays[displayId];
1535 if (!displayDevice->isDisplayOn()) {
1536 continue;
1537 }
1538
David Sodman105b7dc2017-11-04 20:28:14 -07001539 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1540 ALOGE_IF(result != NO_ERROR,
1541 "prepareFrame for display %zd failed:"
1542 " %d (%s)",
1543 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001544 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001545}
1546
Adrian Roos1e1a1282017-11-01 19:05:31 +01001547void SurfaceFlinger::doTracing(const char* where) {
1548 ATRACE_CALL();
1549 ATRACE_NAME(where);
1550 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001551 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001552 }
1553}
1554
Brian Andersond6927fb2016-07-23 23:37:30 -07001555void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001556{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001557 ATRACE_CALL();
1558 ALOGV("preComposition");
1559
Mathias Agopiancd60f992012-08-16 16:28:27 -07001560 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001561 mDrawingState.traverseInZOrder([&](Layer* layer) {
1562 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001563 needExtraInvalidate = true;
1564 }
Robert Carr2047fae2016-11-28 14:09:09 -08001565 });
1566
Mathias Agopiancd60f992012-08-16 16:28:27 -07001567 if (needExtraInvalidate) {
1568 signalLayerUpdate();
1569 }
1570}
1571
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001572void SurfaceFlinger::updateCompositorTiming(
1573 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1574 std::shared_ptr<FenceTime>& presentFenceTime) {
1575 // Update queue of past composite+present times and determine the
1576 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001577 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001578 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001579 while (!getBE().mCompositePresentTimes.empty()) {
1580 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001581 // Cached values should have been updated before calling this method,
1582 // which helps avoid duplicate syscalls.
1583 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1584 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1585 break;
1586 }
1587 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001588 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001589 }
1590
1591 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001592 while (getBE().mCompositePresentTimes.size() > 16) {
1593 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001594 }
1595
Brian Andersond0010582017-03-07 13:20:31 -08001596 setCompositorTimingSnapped(
1597 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1598}
1599
1600void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1601 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001602 // Integer division and modulo round toward 0 not -inf, so we need to
1603 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001604 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001605 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1606 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1607
Brian Andersond0010582017-03-07 13:20:31 -08001608 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1609 if (idealLatency <= 0) {
1610 idealLatency = vsyncInterval;
1611 }
1612
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001613 // Snap the latency to a value that removes scheduling jitter from the
1614 // composition and present times, which often have >1ms of jitter.
1615 // Reducing jitter is important if an app attempts to extrapolate
1616 // something (such as user input) to an accurate diasplay time.
1617 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1618 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001619 nsecs_t bias = vsyncInterval / 2;
1620 int64_t extraVsyncs =
1621 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1622 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1623 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001624
David Sodman99974d22017-11-28 12:04:33 -08001625 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1626 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1627 getBE().mCompositorTiming.interval = vsyncInterval;
1628 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001629}
1630
1631void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001632{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001633 ATRACE_CALL();
1634 ALOGV("postComposition");
1635
Brian Anderson3546a3f2016-07-14 11:51:14 -07001636 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001637 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001638 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001639 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001640 }
1641
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001642 // |mStateLock| not needed as we are on the main thread
1643 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001644
David Sodman73beded2017-11-15 11:56:06 -08001645 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001646 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001647 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001648 glCompositionDoneFenceTime =
1649 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001650 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001651 } else {
1652 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1653 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001654
David Sodman73beded2017-11-15 11:56:06 -08001655 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001656 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001657 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001658 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001659
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001660 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1661 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1662
1663 // We use the refreshStartTime which might be sampled a little later than
1664 // when we started doing work for this frame, but that should be okay
1665 // since updateCompositorTiming has snapping logic.
1666 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001667 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001668 CompositorTiming compositorTiming;
1669 {
David Sodman99974d22017-11-28 12:04:33 -08001670 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1671 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001672 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001673
Robert Carr2047fae2016-11-28 14:09:09 -08001674 mDrawingState.traverseInZOrder([&](Layer* layer) {
1675 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001676 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001677 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001678 recordBufferingStats(layer->getName().string(),
1679 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001680 }
Robert Carr2047fae2016-11-28 14:09:09 -08001681 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001682
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001683 if (presentFenceTime->isValid()) {
1684 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001685 enableHardwareVsync();
1686 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001687 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001688 }
1689 }
1690
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001691 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001692 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001693 enableHardwareVsync();
1694 }
1695 }
1696
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001697 if (mAnimCompositionPending) {
1698 mAnimCompositionPending = false;
1699
Brian Anderson4e606e32017-03-16 15:34:57 -07001700 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001701 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001702 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001703 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001704 // The HWC doesn't support present fences, so use the refresh
1705 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001706 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001707 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001708 mAnimFrameTracker.setActualPresentTime(presentTime);
1709 }
1710 mAnimFrameTracker.advanceFrame();
1711 }
Dan Stozab90cf072015-03-05 11:05:59 -08001712
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001713 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1714 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001715 return;
1716 }
1717
1718 nsecs_t currentTime = systemTime();
1719 if (mHasPoweredOff) {
1720 mHasPoweredOff = false;
1721 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001722 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001723 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001724 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1725 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001726 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001727 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001728 }
David Sodman4a36e932017-11-07 14:29:47 -08001729 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001730 }
David Sodman4a36e932017-11-07 14:29:47 -08001731 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001732}
1733
1734void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001735 ATRACE_CALL();
1736 ALOGV("rebuildLayerStacks");
1737
Mathias Agopiancd60f992012-08-16 16:28:27 -07001738 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001739 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001740 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001741 mVisibleRegionsDirty = false;
1742 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001743
Jeff Sharkey76488112017-02-27 14:15:18 -07001744 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1745 Region opaqueRegion;
1746 Region dirtyRegion;
1747 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001748 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001749 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1750 const Transform& tr(displayDevice->getTransform());
1751 const Rect bounds(displayDevice->getBounds());
1752 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001753 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001754
Jeff Sharkey76488112017-02-27 14:15:18 -07001755 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001756 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001757 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1758 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001759 Region drawRegion(tr.transform(
1760 layer->visibleNonTransparentRegion));
1761 drawRegion.andSelf(bounds);
1762 if (!drawRegion.isEmpty()) {
1763 layersSortedByZ.add(layer);
1764 } else {
1765 // Clear out the HWC layer if this layer was
1766 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001767 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001768 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001769 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001770 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001771 // WM changes displayDevice->layerStack upon sleep/awake.
1772 // Here we make sure we delete the HWC layers even if
1773 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001774 hwcLayerDestroyed = layer->destroyHwcLayer(
1775 displayDevice->getHwcDisplayId());
1776 }
1777
1778 // If a layer is not going to get a release fence because
1779 // it is invisible, but it is also going to release its
1780 // old buffer, add it to the list of layers needing
1781 // fences.
1782 if (hwcLayerDestroyed) {
1783 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1784 mLayersWithQueuedFrames.cend(), layer);
1785 if (found != mLayersWithQueuedFrames.cend()) {
1786 layersNeedingFences.add(layer);
1787 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001788 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001789 });
1790 }
1791 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001792 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001793 displayDevice->undefinedRegion.set(bounds);
1794 displayDevice->undefinedRegion.subtractSelf(
1795 tr.transform(opaqueRegion));
1796 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001797 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001798 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001799}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001800
Romain Guy0147a172017-06-01 13:53:56 -07001801mat4 SurfaceFlinger::computeSaturationMatrix() const {
1802 if (mSaturation == 1.0f) {
1803 return mat4();
1804 }
1805
1806 // Rec.709 luma coefficients
1807 float3 luminance{0.213f, 0.715f, 0.072f};
1808 luminance *= 1.0f - mSaturation;
1809 return mat4(
1810 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1811 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1812 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1813 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1814 );
1815}
1816
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001817// pickColorMode translates a given dataspace into the best available color mode.
1818// Currently only support sRGB and Display-P3.
Peiyong Lina52f0292018-03-14 17:26:31 -07001819ColorMode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Romain Guy54f154a2017-10-24 21:40:32 +01001820 if (mForceNativeColorMode) {
Peiyong Lina52f0292018-03-14 17:26:31 -07001821 return ColorMode::NATIVE;
Romain Guy54f154a2017-10-24 21:40:32 +01001822 }
1823
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001824 switch (dataSpace) {
1825 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1826 // system expects.
1827 case HAL_DATASPACE_UNKNOWN:
1828 case HAL_DATASPACE_SRGB:
1829 case HAL_DATASPACE_V0_SRGB:
Peiyong Lina52f0292018-03-14 17:26:31 -07001830 return ColorMode::SRGB;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001831 break;
1832
1833 case HAL_DATASPACE_DISPLAY_P3:
Peiyong Lina52f0292018-03-14 17:26:31 -07001834 return ColorMode::DISPLAY_P3;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001835 break;
1836
1837 default:
1838 // TODO (courtneygo): Do we want to assert an error here?
1839 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1840 dataSpace);
Peiyong Lina52f0292018-03-14 17:26:31 -07001841 return ColorMode::SRGB;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001842 break;
1843 }
1844}
1845
Romain Guy0147a172017-06-01 13:53:56 -07001846android_dataspace SurfaceFlinger::bestTargetDataSpace(
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001847 android_dataspace a, android_dataspace b, bool hasHdr) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001848 // Only support sRGB and Display-P3 right now.
1849 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1850 return HAL_DATASPACE_DISPLAY_P3;
1851 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001852 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1853 return HAL_DATASPACE_DISPLAY_P3;
1854 }
1855 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1856 return HAL_DATASPACE_DISPLAY_P3;
1857 }
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001858 if (!hasHdr) {
1859 if (a == HAL_DATASPACE_BT2020_PQ || b == HAL_DATASPACE_BT2020_PQ) {
1860 return HAL_DATASPACE_DISPLAY_P3;
1861 }
1862 if (a == HAL_DATASPACE_BT2020_ITU_PQ || b == HAL_DATASPACE_BT2020_ITU_PQ) {
1863 return HAL_DATASPACE_DISPLAY_P3;
1864 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001865 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001866
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001867 return HAL_DATASPACE_V0_SRGB;
1868}
1869
Mathias Agopiancd60f992012-08-16 16:28:27 -07001870void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001871 ATRACE_CALL();
1872 ALOGV("setUpHWComposer");
1873
Jesse Hall028dc8f2013-08-20 16:35:32 -07001874 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001875 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1876 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1877 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1878
1879 // If nothing has changed (!dirty), don't recompose.
1880 // If something changed, but we don't currently have any visible layers,
1881 // and didn't when we last did a composition, then skip it this time.
1882 // The second rule does two things:
1883 // - When all layers are removed from a display, we'll emit one black
1884 // frame, then nothing more until we get new layers.
1885 // - When a display is created with a private layer stack, we won't
1886 // emit any black frames until a layer is added to the layer stack.
1887 bool mustRecompose = dirty && !(empty && wasEmpty);
1888
1889 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1890 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1891 mustRecompose ? "doing" : "skipping",
1892 dirty ? "+" : "-",
1893 empty ? "+" : "-",
1894 wasEmpty ? "+" : "-");
1895
Dan Stoza71433162014-02-04 16:22:36 -08001896 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001897
1898 if (mustRecompose) {
1899 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1900 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001901 }
1902
Dan Stoza9e56aa02015-11-02 13:00:03 -08001903 // build the h/w work list
1904 if (CC_UNLIKELY(mGeometryInvalid)) {
1905 mGeometryInvalid = false;
1906 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1907 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1908 const auto hwcId = displayDevice->getHwcDisplayId();
1909 if (hwcId >= 0) {
1910 const Vector<sp<Layer>>& currentLayers(
1911 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001912 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001913 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001914 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07001915 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001916 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001917 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001918 }
1919 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001920
Robert Carrae060832016-11-28 10:51:00 -08001921 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001922 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001923 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001924 }
1925 }
1926 }
1927 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001928 }
Riley Andrews03414a12014-07-01 14:22:59 -07001929
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001930
Romain Guy0147a172017-06-01 13:53:56 -07001931 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001932
Dan Stoza9e56aa02015-11-02 13:00:03 -08001933 // Set the per-frame data
1934 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1935 auto& displayDevice = mDisplays[displayId];
1936 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001937
Dan Stoza9e56aa02015-11-02 13:00:03 -08001938 if (hwcId < 0) {
1939 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001940 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001941 if (colorMatrix != mPreviousColorMatrix) {
David Sodman105b7dc2017-11-04 20:28:14 -07001942 status_t result = getBE().mHwc->setColorTransform(hwcId, colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001943 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1944 "display %zd: %d", displayId, result);
1945 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001946 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu8d2651e2018-01-24 12:18:49 -08001947 if ((layer->getDataSpace() == HAL_DATASPACE_BT2020_PQ ||
1948 layer->getDataSpace() == HAL_DATASPACE_BT2020_ITU_PQ) &&
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001949 !displayDevice->getHdrSupport()) {
1950 layer->forceClientComposition(hwcId);
1951 }
1952
chaviwc9232ed2017-11-14 15:31:15 -08001953 if (layer->getForceClientComposition(hwcId)) {
1954 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1955 layer->setCompositionType(hwcId, HWC2::Composition::Client);
1956 continue;
1957 }
1958
Dan Stoza9e56aa02015-11-02 13:00:03 -08001959 layer->setPerFrameData(displayDevice);
1960 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001961
1962 if (hasWideColorDisplay) {
Peiyong Lina52f0292018-03-14 17:26:31 -07001963 ColorMode newColorMode;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001964 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1965
1966 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001967 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace,
1968 displayDevice->getHdrSupport());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001969 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1970 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1971 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1972 }
1973 newColorMode = pickColorMode(newDataSpace);
1974
Thierry Strudel2924d012017-08-14 15:19:37 -07001975 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001976 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001977 }
1978
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001979 mPreviousColorMatrix = colorMatrix;
1980
Dan Stoza9e56aa02015-11-02 13:00:03 -08001981 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001982 auto& displayDevice = mDisplays[displayId];
1983 if (!displayDevice->isDisplayOn()) {
1984 continue;
1985 }
1986
David Sodman105b7dc2017-11-04 20:28:14 -07001987 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001988 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1989 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001990 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001991}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001992
Mathias Agopiancd60f992012-08-16 16:28:27 -07001993void SurfaceFlinger::doComposition() {
1994 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001995 ALOGV("doComposition");
1996
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001997 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001998 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001999 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002000 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002001 // transform the dirty region into this screen's coordinate space
2002 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002003
2004 // repaint the framebuffer (if needed)
2005 doDisplayComposition(hw, dirtyRegion);
2006
Mathias Agopiancd60f992012-08-16 16:28:27 -07002007 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002008 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002009 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002010 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002011 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002012}
2013
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002014void SurfaceFlinger::postFramebuffer()
2015{
Mathias Agopian841cde52012-03-01 15:44:37 -08002016 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002017 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002018
Mathias Agopiana44b0412011-10-16 18:46:35 -07002019 const nsecs_t now = systemTime();
2020 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002021
Dan Stoza9e56aa02015-11-02 13:00:03 -08002022 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2023 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002024 if (!displayDevice->isDisplayOn()) {
2025 continue;
2026 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002027 const auto hwcId = displayDevice->getHwcDisplayId();
2028 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002029 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002030 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002031 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002032 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002033 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002034 // The layer buffer from the previous frame (if any) is released
2035 // by HWC only when the release fence from this frame (if any) is
2036 // signaled. Always get the release fence from HWC first.
2037 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002038 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002039
2040 // If the layer was client composited in the previous frame, we
2041 // need to merge with the previous client target acquire fence.
2042 // Since we do not track that, always merge with the current
2043 // client target acquire fence when it is available, even though
2044 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002045 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002046 releaseFence = Fence::merge("LayerRelease", releaseFence,
2047 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002048 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002049
Dan Stoza9e56aa02015-11-02 13:00:03 -08002050 layer->onLayerDisplayed(releaseFence);
2051 }
Chia-I Wu83806892017-11-16 10:50:20 -08002052
2053 // We've got a list of layers needing fences, that are disjoint with
2054 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2055 // supply them with the present fence.
2056 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002057 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002058 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2059 layer->onLayerDisplayed(presentFence);
2060 }
2061 }
2062
Dan Stoza9e56aa02015-11-02 13:00:03 -08002063 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002064 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002065 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002066 }
2067
Mathias Agopiana44b0412011-10-16 18:46:35 -07002068 mLastSwapBufferTime = systemTime() - now;
2069 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002070
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002071 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002072 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2073 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2074 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2075 logFrameStats();
2076 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002077 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002078}
2079
Mathias Agopian87baae12012-07-31 12:38:26 -07002080void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002081{
Mathias Agopian841cde52012-03-01 15:44:37 -08002082 ATRACE_CALL();
2083
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002084 // here we keep a copy of the drawing state (that is the state that's
2085 // going to be overwritten by handleTransactionLocked()) outside of
2086 // mStateLock so that the side-effects of the State assignment
2087 // don't happen with mStateLock held (which can cause deadlocks).
2088 State drawingState(mDrawingState);
2089
Mathias Agopianca4d3602011-05-19 15:38:14 -07002090 Mutex::Autolock _l(mStateLock);
2091 const nsecs_t now = systemTime();
2092 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002093
Mathias Agopianca4d3602011-05-19 15:38:14 -07002094 // Here we're guaranteed that some transaction flags are set
2095 // so we can call handleTransactionLocked() unconditionally.
2096 // We call getTransactionFlags(), which will also clear the flags,
2097 // with mStateLock held to guarantee that mCurrentState won't change
2098 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002099
Mathias Agopiane57f2922012-08-09 16:29:12 -07002100 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002101 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002102
Mathias Agopianca4d3602011-05-19 15:38:14 -07002103 mLastTransactionTime = systemTime() - now;
2104 mDebugInTransaction = 0;
2105 invalidateHwcGeometry();
2106 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002107}
2108
Lloyd Pique715a2c12017-12-14 17:18:08 -08002109DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique09594832018-01-22 17:48:03 -08002110 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002111 // Figure out whether the event is for the primary display or an
2112 // external display by matching the Hwc display id against one for a
2113 // connected display. If we did not find a match, we then check what
2114 // displays are not already connected to determine the type. If we don't
2115 // have a connected primary display, we assume the new display is meant to
2116 // be the primary display, and then if we don't have an external display,
2117 // we assume it is that.
2118 const auto primaryDisplayId =
2119 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2120 const auto externalDisplayId =
2121 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2122 if (primaryDisplayId && primaryDisplayId == display) {
2123 return DisplayDevice::DISPLAY_PRIMARY;
2124 } else if (externalDisplayId && externalDisplayId == display) {
2125 return DisplayDevice::DISPLAY_EXTERNAL;
2126 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2127 return DisplayDevice::DISPLAY_PRIMARY;
2128 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2129 return DisplayDevice::DISPLAY_EXTERNAL;
2130 }
2131
2132 return DisplayDevice::DISPLAY_ID_INVALID;
2133}
2134
Lloyd Piqueba04e622017-12-14 17:11:26 -08002135void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2136 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002137 auto displayType = determineDisplayType(event.display, event.connection);
2138 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2139 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2140 continue;
2141 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002142
2143 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2144 ALOGE("External displays are not supported by the vr hardware composer.");
2145 continue;
2146 }
2147
Lloyd Pique715a2c12017-12-14 17:18:08 -08002148 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002149
2150 if (event.connection == HWC2::Connection::Connected) {
Steven Thomas3bed0522018-03-20 15:40:48 -07002151 if (!mBuiltinDisplays[displayType].get()) {
2152 ALOGV("Creating built in display %d", displayType);
2153 mBuiltinDisplays[displayType] = new BBinder();
2154 // All non-virtual displays are currently considered secure.
2155 DisplayDeviceState info(displayType, true);
2156 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2157 "Built-in Screen" : "External Screen";
2158 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
Lloyd Pique4d234852018-01-22 17:21:36 -08002159 mInterceptor->saveDisplayCreation(info);
Steven Thomas3bed0522018-03-20 15:40:48 -07002160 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002161 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002162 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002163
Lloyd Piquefcd86612017-12-14 17:15:36 -08002164 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2165 if (idx >= 0) {
2166 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Lloyd Pique4d234852018-01-22 17:21:36 -08002167 mInterceptor->saveDisplayDeletion(info.displayId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002168 mCurrentState.displays.removeItemsAt(idx);
2169 }
2170 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002171 }
2172
2173 processDisplayChangesLocked();
2174 }
2175
2176 mPendingHotplugEvents.clear();
2177}
2178
Lloyd Pique09594832018-01-22 17:48:03 -08002179sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2180 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2181 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
2182 bool hasWideColorSupport = false;
2183 if (hasWideColorDisplay) {
2184 std::vector<ColorMode> modes = getHwComposer().getColorModes(state.type);
2185 for (ColorMode colorMode : modes) {
2186 switch (colorMode) {
2187 case ColorMode::DISPLAY_P3:
2188 case ColorMode::ADOBE_RGB:
2189 case ColorMode::DCI_P3:
2190 hasWideColorSupport = true;
2191 break;
2192 default:
2193 break;
2194 }
2195 }
2196 }
2197
2198 bool hasHdrSupport = false;
2199 std::unique_ptr<HdrCapabilities> hdrCapabilities =
2200 getHwComposer().getHdrCapabilities(state.type);
2201 if (hdrCapabilities) {
2202 const std::vector<int32_t> types = hdrCapabilities->getSupportedHdrTypes();
2203 auto iter = std::find(types.cbegin(), types.cend(), HAL_HDR_HDR10);
2204 hasHdrSupport = iter != types.cend();
2205 }
2206
2207 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2208 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2209
2210 /*
2211 * Create our display's surface
2212 */
2213 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2214 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
2215 renderSurface->setAsync(state.type >= DisplayDevice::DISPLAY_VIRTUAL);
2216 renderSurface->setNativeWindow(nativeWindow.get());
2217 const int displayWidth = renderSurface->queryWidth();
2218 const int displayHeight = renderSurface->queryHeight();
2219
2220 // Make sure that composition can never be stalled by a virtual display
2221 // consumer that isn't processing buffers fast enough. We have to do this
2222 // in two places:
2223 // * Here, in case the display is composed entirely by HWC.
2224 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2225 // window's swap interval in eglMakeCurrent, so they'll override the
2226 // interval we set here.
2227 if (state.type >= DisplayDevice::DISPLAY_VIRTUAL) {
2228 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2229 }
2230
2231 // virtual displays are always considered enabled
2232 auto initialPowerMode = (state.type >= DisplayDevice::DISPLAY_VIRTUAL) ? HWC_POWER_MODE_NORMAL
2233 : HWC_POWER_MODE_OFF;
2234
2235 sp<DisplayDevice> hw =
2236 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2237 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
2238 hasWideColorSupport, hasHdrSupport, initialPowerMode);
2239
2240 if (maxFrameBufferAcquiredBuffers >= 3) {
2241 nativeWindowSurface->preallocateBuffers();
2242 }
2243
2244 ColorMode defaultColorMode = ColorMode::NATIVE;
2245 if (hasWideColorSupport) {
2246 defaultColorMode = ColorMode::SRGB;
2247 }
2248 setActiveColorModeInternal(hw, defaultColorMode);
2249 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
2250 hw->setLayerStack(state.layerStack);
2251 hw->setProjection(state.orientation, state.viewport, state.frame);
2252 hw->setDisplayName(state.displayName);
2253
2254 return hw;
2255}
2256
Lloyd Pique347200f2017-12-14 17:00:15 -08002257void SurfaceFlinger::processDisplayChangesLocked() {
2258 // here we take advantage of Vector's copy-on-write semantics to
2259 // improve performance by skipping the transaction entirely when
2260 // know that the lists are identical
2261 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2262 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2263 if (!curr.isIdenticalTo(draw)) {
2264 mVisibleRegionsDirty = true;
2265 const size_t cc = curr.size();
2266 size_t dc = draw.size();
2267
2268 // find the displays that were removed
2269 // (ie: in drawing state but not in current state)
2270 // also handle displays that changed
2271 // (ie: displays that are in both lists)
2272 for (size_t i = 0; i < dc;) {
2273 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2274 if (j < 0) {
2275 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002276 // Call makeCurrent() on the primary display so we can
2277 // be sure that nothing associated with this display
2278 // is current.
2279 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2280 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2281 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2282 if (hw != nullptr) hw->disconnect(getHwComposer());
2283 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2284 mEventThread->onHotplugReceived(draw[i].type, false);
2285 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002286 } else {
2287 // this display is in both lists. see if something changed.
2288 const DisplayDeviceState& state(curr[j]);
2289 const wp<IBinder>& display(curr.keyAt(j));
2290 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2291 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2292 if (state_binder != draw_binder) {
2293 // changing the surface is like destroying and
2294 // recreating the DisplayDevice, so we just remove it
2295 // from the drawing state, so that it get re-added
2296 // below.
2297 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2298 if (hw != nullptr) hw->disconnect(getHwComposer());
2299 mDisplays.removeItem(display);
2300 mDrawingState.displays.removeItemsAt(i);
2301 dc--;
2302 // at this point we must loop to the next item
2303 continue;
2304 }
2305
2306 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2307 if (disp != nullptr) {
2308 if (state.layerStack != draw[i].layerStack) {
2309 disp->setLayerStack(state.layerStack);
2310 }
2311 if ((state.orientation != draw[i].orientation) ||
2312 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2313 disp->setProjection(state.orientation, state.viewport, state.frame);
2314 }
2315 if (state.width != draw[i].width || state.height != draw[i].height) {
2316 disp->setDisplaySize(state.width, state.height);
2317 }
2318 }
2319 }
2320 ++i;
2321 }
2322
2323 // find displays that were added
2324 // (ie: in current state but not in drawing state)
2325 for (size_t i = 0; i < cc; i++) {
2326 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2327 const DisplayDeviceState& state(curr[i]);
2328
2329 sp<DisplaySurface> dispSurface;
2330 sp<IGraphicBufferProducer> producer;
2331 sp<IGraphicBufferProducer> bqProducer;
2332 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002333 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002334
2335 int32_t hwcId = -1;
2336 if (state.isVirtualDisplay()) {
2337 // Virtual displays without a surface are dormant:
2338 // they have external state (layer stack, projection,
2339 // etc.) but no internal state (i.e. a DisplayDevice).
2340 if (state.surface != nullptr) {
2341 // Allow VR composer to use virtual displays.
2342 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2343 int width = 0;
2344 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2345 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2346 int height = 0;
2347 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2348 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2349 int intFormat = 0;
2350 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2351 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2352 auto format = static_cast<android_pixel_format_t>(intFormat);
2353
2354 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2355 }
2356
2357 // TODO: Plumb requested format back up to consumer
2358
2359 sp<VirtualDisplaySurface> vds =
2360 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2361 bqProducer, bqConsumer,
2362 state.displayName);
2363
2364 dispSurface = vds;
2365 producer = vds;
2366 }
2367 } else {
2368 ALOGE_IF(state.surface != nullptr,
2369 "adding a supported display, but rendering "
2370 "surface is provided (%p), ignoring it",
2371 state.surface.get());
2372
2373 hwcId = state.type;
2374 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2375 producer = bqProducer;
2376 }
2377
2378 const wp<IBinder>& display(curr.keyAt(i));
2379 if (dispSurface != nullptr) {
Lloyd Pique09594832018-01-22 17:48:03 -08002380 mDisplays.add(display,
2381 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2382 producer));
Lloyd Pique347200f2017-12-14 17:00:15 -08002383 if (!state.isVirtualDisplay()) {
2384 mEventThread->onHotplugReceived(state.type, true);
2385 }
2386 }
2387 }
2388 }
2389 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002390
2391 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002392}
2393
Mathias Agopian87baae12012-07-31 12:38:26 -07002394void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002395{
Dan Stoza7dde5992015-05-22 09:51:44 -07002396 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002397 mCurrentState.traverseInZOrder([](Layer* layer) {
2398 layer->notifyAvailableFrames();
2399 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002400
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002401 /*
2402 * Traversal of the children
2403 * (perform the transaction for each of them if needed)
2404 */
2405
Mathias Agopian3559b072012-08-15 13:46:03 -07002406 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002407 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002408 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002409 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002410
2411 const uint32_t flags = layer->doTransaction(0);
2412 if (flags & Layer::eVisibleRegion)
2413 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002414 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002415 }
2416
2417 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002418 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002419 */
2420
Mathias Agopiane57f2922012-08-09 16:29:12 -07002421 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002422 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002423 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002424 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002425
Mathias Agopian84300952012-11-21 16:02:13 -08002426 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2427 // The transform hint might have changed for some layers
2428 // (either because a display has changed, or because a layer
2429 // as changed).
2430 //
2431 // Walk through all the layers in currentLayers,
2432 // and update their transform hint.
2433 //
2434 // If a layer is visible only on a single display, then that
2435 // display is used to calculate the hint, otherwise we use the
2436 // default display.
2437 //
2438 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2439 // the hint is set before we acquire a buffer from the surface texture.
2440 //
2441 // NOTE: layer transactions have taken place already, so we use their
2442 // drawing state. However, SurfaceFlinger's own transaction has not
2443 // happened yet, so we must use the current state layer list
2444 // (soon to become the drawing state list).
2445 //
2446 sp<const DisplayDevice> disp;
2447 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002448 bool first = true;
2449 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002450 // NOTE: we rely on the fact that layers are sorted by
2451 // layerStack first (so we don't have to traverse the list
2452 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002453 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002454 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002455 currentlayerStack = layerStack;
2456 // figure out if this layerstack is mirrored
2457 // (more than one display) if so, pick the default display,
2458 // if not, pick the only display it's on.
2459 disp.clear();
2460 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2461 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002462 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002463 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002464 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002465 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002466 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002467 break;
2468 }
2469 }
2470 }
2471 }
Chet Haase91d25932013-04-11 15:24:55 -07002472
Robert Carr56a0b9a2017-12-04 16:06:13 -08002473 if (transactionFlags & eDisplayTransactionNeeded) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002474 if (disp == nullptr) {
Robert Carr56a0b9a2017-12-04 16:06:13 -08002475 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2476 // redraw after transform hint changes. See bug 8508397.
2477
2478 // could be null when this layer is using a layerStack
2479 // that is not visible on any display. Also can occur at
2480 // screen off/on times.
2481 disp = getDefaultDisplayDeviceLocked();
2482 }
2483 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08002484 }
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002485 if (disp != nullptr) {
2486 layer->updateTransformHint(disp);
2487 }
Robert Carr2047fae2016-11-28 14:09:09 -08002488
2489 first = false;
2490 });
Mathias Agopian84300952012-11-21 16:02:13 -08002491 }
2492
2493
Mathias Agopian3559b072012-08-15 13:46:03 -07002494 /*
2495 * Perform our own transaction if needed
2496 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002497
2498 if (mLayersAdded) {
2499 mLayersAdded = false;
2500 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002501 mVisibleRegionsDirty = true;
2502 }
2503
2504 // some layers might have been removed, so
2505 // we need to update the regions they're exposing.
2506 if (mLayersRemoved) {
2507 mLayersRemoved = false;
2508 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002509 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002510 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002511 // this layer is not visible anymore
2512 // TODO: we could traverse the tree from front to back and
2513 // compute the actual visible region
2514 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002515 Region visibleReg;
2516 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002517 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002518 }
Robert Carr2047fae2016-11-28 14:09:09 -08002519 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002520 }
2521
2522 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002523
2524 updateCursorAsync();
2525}
2526
2527void SurfaceFlinger::updateCursorAsync()
2528{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002529 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2530 auto& displayDevice = mDisplays[displayId];
2531 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002532 continue;
2533 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002534
2535 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2536 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002537 }
2538 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002539}
2540
2541void SurfaceFlinger::commitTransaction()
2542{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002543 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002544 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002545 for (const auto& l : mLayersPendingRemoval) {
2546 recordBufferingStats(l->getName().string(),
2547 l->getOccupancyHistory(true));
2548 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002549 }
2550 mLayersPendingRemoval.clear();
2551 }
2552
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002553 // If this transaction is part of a window animation then the next frame
2554 // we composite should be considered an animation as well.
2555 mAnimCompositionPending = mAnimTransactionPending;
2556
Mathias Agopian4fec8732012-06-29 14:12:52 -07002557 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002558 mDrawingState.traverseInZOrder([](Layer* layer) {
2559 layer->commitChildList();
2560 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002561 mTransactionPending = false;
2562 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002563 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002564}
2565
Chia-I Wuab0c3192017-08-01 11:29:00 -07002566void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002567 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002568{
Mathias Agopian841cde52012-03-01 15:44:37 -08002569 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002570 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002571
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002572 Region aboveOpaqueLayers;
2573 Region aboveCoveredLayers;
2574 Region dirty;
2575
Mathias Agopian87baae12012-07-31 12:38:26 -07002576 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002577
Robert Carr2047fae2016-11-28 14:09:09 -08002578 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002579 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002580 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002581
Jesse Hall01e29052013-02-19 16:13:35 -08002582 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002583 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002584 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002585
Mathias Agopianab028732010-03-16 16:41:46 -07002586 /*
2587 * opaqueRegion: area of a surface that is fully opaque.
2588 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002589 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002590
2591 /*
2592 * visibleRegion: area of a surface that is visible on screen
2593 * and not fully transparent. This is essentially the layer's
2594 * footprint minus the opaque regions above it.
2595 * Areas covered by a translucent surface are considered visible.
2596 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002597 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002598
2599 /*
2600 * coveredRegion: area of a surface that is covered by all
2601 * visible regions above it (which includes the translucent areas).
2602 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002603 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002604
Jesse Halla8026d22012-09-25 13:25:04 -07002605 /*
2606 * transparentRegion: area of a surface that is hinted to be completely
2607 * transparent. This is only used to tell when the layer has no visible
2608 * non-transparent regions and can be removed from the layer list. It
2609 * does not affect the visibleRegion of this layer or any layers
2610 * beneath it. The hint may not be correct if apps don't respect the
2611 * SurfaceView restrictions (which, sadly, some don't).
2612 */
2613 Region transparentRegion;
2614
Mathias Agopianab028732010-03-16 16:41:46 -07002615
2616 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002617 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002618 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002619 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002620 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002621 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002622 if (!visibleRegion.isEmpty()) {
2623 // Remove the transparent area from the visible region
2624 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002625 if (tr.preserveRects()) {
2626 // transform the transparent region
2627 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002628 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002629 // transformation too complex, can't do the
2630 // transparent region optimization.
2631 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002632 }
Mathias Agopianab028732010-03-16 16:41:46 -07002633 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002634
Mathias Agopianab028732010-03-16 16:41:46 -07002635 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002636 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002637 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002638 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2639 // the opaque region is the layer's footprint
2640 opaqueRegion = visibleRegion;
2641 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002642 }
2643 }
2644
Robert Carre5f4f692018-01-12 13:12:28 -08002645 if (visibleRegion.isEmpty()) {
2646 layer->clearVisibilityRegions();
2647 return;
2648 }
2649
Mathias Agopianab028732010-03-16 16:41:46 -07002650 // Clip the covered region to the visible region
2651 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2652
2653 // Update aboveCoveredLayers for next (lower) layer
2654 aboveCoveredLayers.orSelf(visibleRegion);
2655
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002656 // subtract the opaque region covered by the layers above us
2657 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002658
2659 // compute this layer's dirty region
2660 if (layer->contentDirty) {
2661 // we need to invalidate the whole region
2662 dirty = visibleRegion;
2663 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002664 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002665 layer->contentDirty = false;
2666 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002667 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002668 * the exposed region consists of two components:
2669 * 1) what's VISIBLE now and was COVERED before
2670 * 2) what's EXPOSED now less what was EXPOSED before
2671 *
2672 * note that (1) is conservative, we start with the whole
2673 * visible region but only keep what used to be covered by
2674 * something -- which mean it may have been exposed.
2675 *
2676 * (2) handles areas that were not covered by anything but got
2677 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002678 */
Mathias Agopianab028732010-03-16 16:41:46 -07002679 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002680 const Region oldVisibleRegion = layer->visibleRegion;
2681 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002682 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2683 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002684 }
2685 dirty.subtractSelf(aboveOpaqueLayers);
2686
2687 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002688 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002689
Mathias Agopianab028732010-03-16 16:41:46 -07002690 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002691 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002692
Jesse Halla8026d22012-09-25 13:25:04 -07002693 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002694 layer->setVisibleRegion(visibleRegion);
2695 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002696 layer->setVisibleNonTransparentRegion(
2697 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002698 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002699
Mathias Agopian87baae12012-07-31 12:38:26 -07002700 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002701}
2702
Chia-I Wuab0c3192017-08-01 11:29:00 -07002703void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002704 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002705 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002706 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002707 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002708 }
2709 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002710}
2711
Dan Stoza6b9454d2014-11-07 16:00:59 -08002712bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002713{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002714 ALOGV("handlePageFlip");
2715
Brian Andersond6927fb2016-07-23 23:37:30 -07002716 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002717
Mathias Agopian4fec8732012-06-29 14:12:52 -07002718 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002719 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002720 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002721
2722 // Store the set of layers that need updates. This set must not change as
2723 // buffers are being latched, as this could result in a deadlock.
2724 // Example: Two producers share the same command stream and:
2725 // 1.) Layer 0 is latched
2726 // 2.) Layer 0 gets a new frame
2727 // 2.) Layer 1 gets a new frame
2728 // 3.) Layer 1 is latched.
2729 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2730 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002731 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002732 if (layer->hasQueuedFrame()) {
2733 frameQueued = true;
2734 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002735 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002736 } else {
2737 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002738 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002739 } else {
2740 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002741 }
Robert Carr2047fae2016-11-28 14:09:09 -08002742 });
2743
Dan Stoza9e56aa02015-11-02 13:00:03 -08002744 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002745 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002746 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002747 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002748 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002749 newDataLatched = true;
2750 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002751 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002752
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002753 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002754
2755 // If we will need to wake up at some time in the future to deal with a
2756 // queued frame that shouldn't be displayed during this vsync period, wake
2757 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002758 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002759 signalLayerUpdate();
2760 }
2761
2762 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002763 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002764}
2765
Mathias Agopianad456f92011-01-13 17:53:01 -08002766void SurfaceFlinger::invalidateHwcGeometry()
2767{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002768 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002769}
2770
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002771
Fabien Sanglard830b8472016-11-30 16:35:58 -08002772void SurfaceFlinger::doDisplayComposition(
2773 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002774 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002775{
Dan Stoza71433162014-02-04 16:22:36 -08002776 // We only need to actually compose the display if:
2777 // 1) It is being handled by hardware composer, which may need this to
2778 // keep its virtual display state machine in sync, or
2779 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002780 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002781 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002782 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002783 return;
2784 }
2785
Dan Stoza9e56aa02015-11-02 13:00:03 -08002786 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002787 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002788
2789 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002790 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002791}
2792
Chia-I Wub02087d2017-11-09 10:19:54 -08002793bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002794{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002795 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002796
Chia-I Wub02087d2017-11-09 10:19:54 -08002797 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002798 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002799 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002800
2801 mat4 oldColorMatrix;
David Sodman105b7dc2017-11-04 20:28:14 -07002802 const bool applyColorMatrix = !getBE().mHwc->hasDeviceComposition(hwcId) &&
2803 !getBE().mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002804 if (applyColorMatrix) {
2805 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2806 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2807 }
2808
David Sodman105b7dc2017-11-04 20:28:14 -07002809 bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002810 if (hasClientComposition) {
2811 ALOGV("hasClientComposition");
2812
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002813 android_dataspace outputDataspace = HAL_DATASPACE_UNKNOWN;
Chia-I Wu9a48a8c2018-02-20 14:27:30 -08002814 if (displayDevice->getWideColorSupport() &&
Peiyong Lina52f0292018-03-14 17:26:31 -07002815 displayDevice->getActiveColorMode() == ColorMode::DISPLAY_P3) {
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002816 outputDataspace = HAL_DATASPACE_DISPLAY_P3;
2817 }
2818 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
2819
Chia-I Wu7f402902017-11-09 12:51:10 -08002820 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002821 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002822 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002823 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002824
2825 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002826 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002827 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2828 }
2829 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002830 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002831
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002832 // Never touch the framebuffer if we don't have any framebuffer layers
David Sodman105b7dc2017-11-04 20:28:14 -07002833 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002834 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002835 // when using overlays, we assume a fully transparent framebuffer
2836 // NOTE: we could reduce how much we need to clear, for instance
2837 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002838 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002839 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002840 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002841 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002842 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002843 // we're left with the letterbox region
2844 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002845 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002846
2847 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002848 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002849
Mathias Agopianb9494d52012-04-18 02:28:45 -07002850 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002851 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002852 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002853 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002854 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002855 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002856
Dan Stoza9e56aa02015-11-02 13:00:03 -08002857 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002858 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002859 // scissor on the main display. It should never be needed
2860 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002861 const Rect& bounds(displayDevice->getBounds());
2862 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002863 if (scissor != bounds) {
2864 // scissor doesn't match the screen's dimensions, so we
2865 // need to clear everything outside of it and enable
2866 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002867
Mathias Agopianf45c5102012-10-24 16:29:17 -07002868 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002869 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002870 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002871 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002872 }
2873 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002874 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002875
Mathias Agopian85d751c2012-08-29 16:59:24 -07002876 /*
2877 * and then, render the layers targeted at the framebuffer
2878 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002879
Dan Stoza9e56aa02015-11-02 13:00:03 -08002880 ALOGV("Rendering client layers");
2881 const Transform& displayTransform = displayDevice->getTransform();
2882 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002883 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002884 bool firstLayer = true;
2885 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002886 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002887 displayTransform.transform(layer->visibleRegion)));
2888 ALOGV("Layer: %s", layer->getName().string());
2889 ALOGV(" Composition type: %s",
2890 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002891 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002892 switch (layer->getCompositionType(hwcId)) {
2893 case HWC2::Composition::Cursor:
2894 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002895 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002896 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002897 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002898 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002899 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002900 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002901 // never clear the very first layer since we're
2902 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002903 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002904 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002905 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002906 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002907 case HWC2::Composition::Client: {
chaviwa76b2712017-09-20 12:02:26 -07002908 layer->draw(renderArea, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002909 break;
2910 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002911 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002912 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002913 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002914 } else {
2915 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002916 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002917 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002918 }
2919 } else {
2920 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002921 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002922 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002923 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002924 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07002925 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002926 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002927 }
2928 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002929
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002930 if (applyColorMatrix) {
2931 getRenderEngine().setupColorTransform(oldColorMatrix);
2932 }
2933
Mathias Agopianf45c5102012-10-24 16:29:17 -07002934 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002935 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002936 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002937}
2938
Fabien Sanglard830b8472016-11-30 16:35:58 -08002939void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2940 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08002941 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07002942 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002943}
2944
Dan Stoza7d89d062015-04-30 13:29:25 -07002945status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002946 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002947 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002948 const sp<Layer>& lbc,
2949 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002950{
Dan Stoza7d89d062015-04-30 13:29:25 -07002951 // add this layer to the current state list
2952 {
2953 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002954 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002955 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2956 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002957 return NO_MEMORY;
2958 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002959 if (parent == nullptr) {
2960 mCurrentState.layersSortedByZ.add(lbc);
2961 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08002962 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002963 ALOGE("addClientLayer called with a removed parent");
2964 return NAME_NOT_FOUND;
2965 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002966 parent->addChild(lbc);
2967 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002968
Dan Stoza101d8dc2018-02-27 15:42:25 -08002969 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
Dan Stoza0a0158c2018-03-16 13:38:54 -07002970 // TODO (b/74616334): Change this back to a fatal assert once the leak is fixed
2971 ALOGE_IF(mGraphicBufferProducerList.size() > mMaxGraphicBufferProducerListSize,
2972 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
2973 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize,
2974 mNumLayers);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002975 mLayersAdded = true;
2976 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002977 }
2978
Mathias Agopian96f08192010-06-02 23:28:45 -07002979 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002980 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002981
Dan Stoza7d89d062015-04-30 13:29:25 -07002982 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002983}
2984
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002985status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002986 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08002987 return removeLayerLocked(mStateLock, layer, topLevelOnly);
2988}
Robert Carr7f9b8992017-03-10 11:08:39 -08002989
chaviwca27f252018-02-06 16:46:39 -08002990status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
2991 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07002992 if (layer->isPendingRemoval()) {
2993 return NO_ERROR;
2994 }
2995
Robert Carr1f0a16a2016-10-24 16:27:39 -07002996 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002997 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002998 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002999 if (topLevelOnly) {
3000 return NO_ERROR;
3001 }
3002
Chia-I Wu98f1c102017-05-30 14:54:08 -07003003 sp<Layer> ancestor = p;
3004 while (ancestor->getParent() != nullptr) {
3005 ancestor = ancestor->getParent();
3006 }
3007 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3008 ALOGE("removeLayer called with a layer whose parent has been removed");
3009 return NAME_NOT_FOUND;
3010 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003011
3012 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003013 } else {
3014 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003015 }
3016
Robert Carr136e2f62017-02-08 17:54:29 -08003017 // As a matter of normal operation, the LayerCleaner will produce a second
3018 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3019 // so we will succeed in promoting it, but it's already been removed
3020 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3021 // otherwise something has gone wrong and we are leaking the layer.
3022 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003023 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3024 layer->getName().string(),
3025 (p != nullptr) ? p->getName().string() : "no-parent");
3026 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003027 } else if (index < 0) {
3028 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003029 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003030
Chia-I Wuc6657022017-08-15 11:18:17 -07003031 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003032 mLayersPendingRemoval.add(layer);
3033 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003034 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003035 setTransactionFlags(eTransactionNeeded);
3036 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003037}
3038
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003039uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003040 return android_atomic_release_load(&mTransactionFlags);
3041}
3042
Mathias Agopian3f844832013-08-07 21:24:32 -07003043uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003044 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3045}
3046
Mathias Agopian3f844832013-08-07 21:24:32 -07003047uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003048 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
3049 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003050 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003051 }
3052 return old;
3053}
3054
chaviwca27f252018-02-06 16:46:39 -08003055bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3056 for (const ComposerState& state : states) {
3057 // Here we need to check that the interface we're given is indeed
3058 // one of our own. A malicious client could give us a nullptr
3059 // IInterface, or one of its own or even one of our own but a
3060 // different type. All these situations would cause us to crash.
3061 if (state.client == nullptr) {
3062 return true;
3063 }
3064
3065 sp<IBinder> binder = IInterface::asBinder(state.client);
3066 if (binder == nullptr) {
3067 return true;
3068 }
3069
3070 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3071 return true;
3072 }
3073 }
3074 return false;
3075}
3076
Mathias Agopian8b33f032012-07-24 20:43:54 -07003077void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003078 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003079 const Vector<DisplayState>& displays,
3080 uint32_t flags)
3081{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003082 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003083 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003084 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003085
chaviwca27f252018-02-06 16:46:39 -08003086 if (containsAnyInvalidClientState(states)) {
3087 return;
3088 }
3089
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003090 if (flags & eAnimation) {
3091 // For window updates that are part of an animation we must wait for
3092 // previous animation "frames" to be handled.
3093 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003094 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003095 if (CC_UNLIKELY(err != NO_ERROR)) {
3096 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003097 // caller after a few seconds.
3098 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3099 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003100 mAnimTransactionPending = false;
3101 break;
3102 }
3103 }
3104 }
3105
chaviwca27f252018-02-06 16:46:39 -08003106 for (const DisplayState& display : displays) {
3107 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003108 }
3109
chaviwca27f252018-02-06 16:46:39 -08003110 for (const ComposerState& state : states) {
3111 transactionFlags |= setClientStateLocked(state);
3112 }
3113
3114 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3115 // as destroyed should only occur after setting all other states. This is to allow for a
3116 // child re-parent to happen before marking its original parent as destroyed (which would
3117 // then mark the child as destroyed).
3118 for (const ComposerState& state : states) {
3119 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003120 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003121
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003122 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3123 // anyway. This can be used as a flush mechanism for previous async transactions.
3124 // Empty animation transaction can be used to simulate back-pressure, so also force a
3125 // transaction for empty animation transactions.
3126 if (transactionFlags == 0 &&
3127 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003128 transactionFlags = eTransactionNeeded;
3129 }
3130
Mathias Agopian386aa982011-11-07 21:58:03 -08003131 if (transactionFlags) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003132 if (mInterceptor->isEnabled()) {
3133 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003134 }
Irvel468051e2016-06-13 16:44:44 -07003135
Mathias Agopian386aa982011-11-07 21:58:03 -08003136 // this triggers the transaction
3137 setTransactionFlags(transactionFlags);
3138
3139 // if this is a synchronous transaction, wait for it to take effect
3140 // before returning.
3141 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003142 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003143 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003144 if (flags & eAnimation) {
3145 mAnimTransactionPending = true;
3146 }
3147 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003148 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3149 if (CC_UNLIKELY(err != NO_ERROR)) {
3150 // just in case something goes wrong in SF, return to the
3151 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003152 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3153 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003154 break;
3155 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003156 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003157 }
3158}
3159
Mathias Agopiane57f2922012-08-09 16:29:12 -07003160uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3161{
Jesse Hall9a143922012-10-04 16:29:19 -07003162 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3163 if (dpyIdx < 0)
3164 return 0;
3165
Mathias Agopiane57f2922012-08-09 16:29:12 -07003166 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003167 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003168 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003169 const uint32_t what = s.what;
3170 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003171 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003172 disp.surface = s.surface;
3173 flags |= eDisplayTransactionNeeded;
3174 }
3175 }
3176 if (what & DisplayState::eLayerStackChanged) {
3177 if (disp.layerStack != s.layerStack) {
3178 disp.layerStack = s.layerStack;
3179 flags |= eDisplayTransactionNeeded;
3180 }
3181 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003182 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003183 if (disp.orientation != s.orientation) {
3184 disp.orientation = s.orientation;
3185 flags |= eDisplayTransactionNeeded;
3186 }
3187 if (disp.frame != s.frame) {
3188 disp.frame = s.frame;
3189 flags |= eDisplayTransactionNeeded;
3190 }
3191 if (disp.viewport != s.viewport) {
3192 disp.viewport = s.viewport;
3193 flags |= eDisplayTransactionNeeded;
3194 }
3195 }
Michael Lentine47e45402014-07-18 15:34:25 -07003196 if (what & DisplayState::eDisplaySizeChanged) {
3197 if (disp.width != s.width) {
3198 disp.width = s.width;
3199 flags |= eDisplayTransactionNeeded;
3200 }
3201 if (disp.height != s.height) {
3202 disp.height = s.height;
3203 flags |= eDisplayTransactionNeeded;
3204 }
3205 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003206 }
3207 return flags;
3208}
3209
chaviwca27f252018-02-06 16:46:39 -08003210uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3211 const layer_state_t& s = composerState.state;
3212 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3213
Mathias Agopian13127d82013-03-05 17:47:11 -08003214 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003215 if (layer == nullptr) {
3216 return 0;
3217 }
3218
3219 if (layer->isPendingRemoval()) {
3220 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3221 return 0;
3222 }
3223
3224 uint32_t flags = 0;
3225
3226 const uint32_t what = s.what;
3227 bool geometryAppliesWithResize =
3228 what & layer_state_t::eGeometryAppliesWithResize;
3229 if (what & layer_state_t::ePositionChanged) {
3230 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3231 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003232 }
chaviw8b3871a2017-11-01 17:41:01 -07003233 }
3234 if (what & layer_state_t::eLayerChanged) {
3235 // NOTE: index needs to be calculated before we update the state
3236 const auto& p = layer->getParent();
3237 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003238 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003239 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003240 mCurrentState.layersSortedByZ.removeAt(idx);
3241 mCurrentState.layersSortedByZ.add(layer);
3242 // we need traversal (state changed)
3243 // AND transaction (list changed)
3244 flags |= eTransactionNeeded|eTraversalNeeded;
3245 }
chaviw8b3871a2017-11-01 17:41:01 -07003246 } else {
3247 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003248 flags |= eTransactionNeeded|eTraversalNeeded;
3249 }
3250 }
chaviw8b3871a2017-11-01 17:41:01 -07003251 }
3252 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003253 // NOTE: index needs to be calculated before we update the state
3254 const auto& p = layer->getParent();
3255 if (p == nullptr) {
3256 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3257 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3258 mCurrentState.layersSortedByZ.removeAt(idx);
3259 mCurrentState.layersSortedByZ.add(layer);
3260 // we need traversal (state changed)
3261 // AND transaction (list changed)
3262 flags |= eTransactionNeeded|eTraversalNeeded;
3263 }
3264 } else {
3265 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3266 flags |= eTransactionNeeded|eTraversalNeeded;
3267 }
chaviw8b3871a2017-11-01 17:41:01 -07003268 }
3269 }
3270 if (what & layer_state_t::eSizeChanged) {
3271 if (layer->setSize(s.w, s.h)) {
3272 flags |= eTraversalNeeded;
3273 }
3274 }
3275 if (what & layer_state_t::eAlphaChanged) {
3276 if (layer->setAlpha(s.alpha))
3277 flags |= eTraversalNeeded;
3278 }
3279 if (what & layer_state_t::eColorChanged) {
3280 if (layer->setColor(s.color))
3281 flags |= eTraversalNeeded;
3282 }
3283 if (what & layer_state_t::eMatrixChanged) {
3284 if (layer->setMatrix(s.matrix))
3285 flags |= eTraversalNeeded;
3286 }
3287 if (what & layer_state_t::eTransparentRegionChanged) {
3288 if (layer->setTransparentRegionHint(s.transparentRegion))
3289 flags |= eTraversalNeeded;
3290 }
3291 if (what & layer_state_t::eFlagsChanged) {
3292 if (layer->setFlags(s.flags, s.mask))
3293 flags |= eTraversalNeeded;
3294 }
3295 if (what & layer_state_t::eCropChanged) {
3296 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3297 flags |= eTraversalNeeded;
3298 }
3299 if (what & layer_state_t::eFinalCropChanged) {
3300 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3301 flags |= eTraversalNeeded;
3302 }
3303 if (what & layer_state_t::eLayerStackChanged) {
3304 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3305 // We only allow setting layer stacks for top level layers,
3306 // everything else inherits layer stack from its parent.
3307 if (layer->hasParent()) {
3308 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3309 layer->getName().string());
3310 } else if (idx < 0) {
3311 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3312 "that also does not appear in the top level layer list. Something"
3313 " has gone wrong.", layer->getName().string());
3314 } else if (layer->setLayerStack(s.layerStack)) {
3315 mCurrentState.layersSortedByZ.removeAt(idx);
3316 mCurrentState.layersSortedByZ.add(layer);
3317 // we need traversal (state changed)
3318 // AND transaction (list changed)
3319 flags |= eTransactionNeeded|eTraversalNeeded;
3320 }
3321 }
3322 if (what & layer_state_t::eDeferTransaction) {
3323 if (s.barrierHandle != nullptr) {
3324 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3325 } else if (s.barrierGbp != nullptr) {
3326 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3327 if (authenticateSurfaceTextureLocked(gbp)) {
3328 const auto& otherLayer =
3329 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3330 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3331 } else {
3332 ALOGE("Attempt to defer transaction to to an"
3333 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003334 }
3335 }
chaviw8b3871a2017-11-01 17:41:01 -07003336 // We don't trigger a traversal here because if no other state is
3337 // changed, we don't want this to cause any more work
3338 }
3339 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003340 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003341 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003342 if (!hadParent) {
3343 mCurrentState.layersSortedByZ.remove(layer);
3344 }
chaviw8b3871a2017-11-01 17:41:01 -07003345 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003346 }
chaviw8b3871a2017-11-01 17:41:01 -07003347 }
3348 if (what & layer_state_t::eReparentChildren) {
3349 if (layer->reparentChildren(s.reparentHandle)) {
3350 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003351 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003352 }
chaviw8b3871a2017-11-01 17:41:01 -07003353 if (what & layer_state_t::eDetachChildren) {
3354 layer->detachChildren();
3355 }
3356 if (what & layer_state_t::eOverrideScalingModeChanged) {
3357 layer->setOverrideScalingMode(s.overrideScalingMode);
3358 // We don't trigger a traversal here because if no other state is
3359 // changed, we don't want this to cause any more work
3360 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003361 return flags;
3362}
3363
chaviwca27f252018-02-06 16:46:39 -08003364void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3365 const layer_state_t& state = composerState.state;
3366 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3367
3368 sp<Layer> layer(client->getLayerUser(state.surface));
3369 if (layer == nullptr) {
3370 return;
3371 }
3372
3373 if (layer->isPendingRemoval()) {
3374 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3375 return;
3376 }
3377
3378 if (state.what & layer_state_t::eDestroySurface) {
3379 removeLayerLocked(mStateLock, layer);
3380 }
3381}
3382
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003383status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003384 const String8& name,
3385 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003386 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliuccd34842018-03-14 12:26:23 -07003387 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003388 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003389{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003390 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003391 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003392 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003393 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003394 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003395
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003396 status_t result = NO_ERROR;
3397
3398 sp<Layer> layer;
3399
Cody Northropbc755282017-03-31 12:00:08 -06003400 String8 uniqueName = getUniqueLayerName(name);
3401
Mathias Agopian3165cc22012-08-08 19:42:09 -07003402 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3403 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003404 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003405 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003406 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003407
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003408 break;
chaviw13fdc492017-06-27 12:40:18 -07003409 case ISurfaceComposerClient::eFXSurfaceColor:
3410 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003411 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003412 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003413 break;
3414 default:
3415 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003416 break;
3417 }
3418
Dan Stoza7d89d062015-04-30 13:29:25 -07003419 if (result != NO_ERROR) {
3420 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003421 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003422
Chia-I Wuab0c3192017-08-01 11:29:00 -07003423 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3424 // TODO b/64227542
3425 if (windowType == 441731) {
3426 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3427 layer->setPrimaryDisplayOnly();
3428 }
3429
Albert Chaulk479c60c2017-01-27 14:21:34 -05003430 layer->setInfo(windowType, ownerUid);
3431
Robert Carr1f0a16a2016-10-24 16:27:39 -07003432 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003433 if (result != NO_ERROR) {
3434 return result;
3435 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003436 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003437
3438 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003439 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003440}
3441
Cody Northropbc755282017-03-31 12:00:08 -06003442String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3443{
3444 bool matchFound = true;
3445 uint32_t dupeCounter = 0;
3446
3447 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3448 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3449
3450 // Loop over layers until we're sure there is no matching name
3451 while (matchFound) {
3452 matchFound = false;
3453 mDrawingState.traverseInZOrder([&](Layer* layer) {
3454 if (layer->getName() == uniqueName) {
3455 matchFound = true;
3456 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3457 }
3458 });
3459 }
3460
3461 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3462
3463 return uniqueName;
3464}
3465
David Sodman0c69cad2017-08-21 12:12:51 -07003466status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003467 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3468 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003469{
3470 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003471 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003472 case PIXEL_FORMAT_TRANSPARENT:
3473 case PIXEL_FORMAT_TRANSLUCENT:
3474 format = PIXEL_FORMAT_RGBA_8888;
3475 break;
3476 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003477 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003478 break;
3479 }
3480
David Sodman0c69cad2017-08-21 12:12:51 -07003481 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3482 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003483 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003484 *handle = layer->getHandle();
3485 *gbp = layer->getProducer();
3486 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003487 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003488
David Sodman0c69cad2017-08-21 12:12:51 -07003489 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003490 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003491}
3492
chaviw13fdc492017-06-27 12:40:18 -07003493status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003494 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003495 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003496{
chaviw13fdc492017-06-27 12:40:18 -07003497 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003498 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003499 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003500}
3501
Mathias Agopianac9fa422013-02-11 16:40:36 -08003502status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003503{
Robert Carr9524cb32017-02-13 11:32:32 -08003504 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003505 status_t err = NO_ERROR;
3506 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003507 if (l != nullptr) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003508 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003509 err = removeLayer(l);
3510 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3511 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003512 }
3513 return err;
3514}
3515
Mathias Agopian13127d82013-03-05 17:47:11 -08003516status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003517{
Mathias Agopian67106042013-03-14 19:18:13 -07003518 // called by ~LayerCleaner() when all references to the IBinder (handle)
3519 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003520 sp<Layer> l = layer.promote();
3521 if (l == nullptr) {
3522 // The layer has already been removed, carry on
3523 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003524 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003525 // If we have a parent, then we can continue to live as long as it does.
3526 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003527}
3528
Mathias Agopianb60314a2012-04-10 22:09:54 -07003529// ---------------------------------------------------------------------------
3530
Andy McFadden13a082e2012-08-24 10:16:42 -07003531void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003532 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003533 Vector<ComposerState> state;
3534 Vector<DisplayState> displays;
3535 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003536 d.what = DisplayState::eDisplayProjectionChanged |
3537 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003538 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003539 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003540 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003541 d.frame.makeInvalid();
3542 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003543 d.width = 0;
3544 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003545 displays.add(d);
3546 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003547 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3548 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003549
David Sodman105b7dc2017-11-04 20:28:14 -07003550 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003551 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003552 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003553
Brian Andersond0010582017-03-07 13:20:31 -08003554 // Use phase of 0 since phase is not known.
3555 // Use latency of 0, which will snap to the ideal latency.
3556 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003557}
3558
3559void SurfaceFlinger::initializeDisplays() {
3560 class MessageScreenInitialized : public MessageBase {
3561 SurfaceFlinger* flinger;
3562 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003563 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003564 virtual bool handler() {
3565 flinger->onInitializeDisplays();
3566 return true;
3567 }
3568 };
3569 sp<MessageBase> msg = new MessageScreenInitialized(this);
3570 postMessageAsync(msg); // we may be called from main thread, use async message
3571}
3572
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003573void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003574 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003575 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3576 this);
3577 int32_t type = hw->getDisplayType();
3578 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003579
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003580 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003581 return;
3582 }
3583
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003584 hw->setPowerMode(mode);
3585 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3586 ALOGW("Trying to set power mode for virtual display");
3587 return;
3588 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003589
Lloyd Pique4d234852018-01-22 17:21:36 -08003590 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003591 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003592 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3593 if (idx < 0) {
3594 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3595 return;
3596 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003597 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003598 }
3599
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003600 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003601 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003602 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003603 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3604 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003605 // FIXME: eventthread only knows about the main display right now
3606 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003607 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003608 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003609
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003610 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003611 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003612 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003613
3614 struct sched_param param = {0};
3615 param.sched_priority = 1;
3616 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3617 ALOGW("Couldn't set SCHED_FIFO on display on");
3618 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003619 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003620 // Turn off the display
3621 struct sched_param param = {0};
3622 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3623 ALOGW("Couldn't set SCHED_OTHER on display off");
3624 }
3625
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003626 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3627 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003628 disableHardwareVsync(true); // also cancels any in-progress resync
3629
Mathias Agopiancde87a32012-09-13 14:09:01 -07003630 // FIXME: eventthread only knows about the main display right now
3631 mEventThread->onScreenReleased();
3632 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003633
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003634 getHwComposer().setPowerMode(type, mode);
3635 mVisibleRegionsDirty = true;
3636 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003637 } else if (mode == HWC_POWER_MODE_DOZE ||
3638 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003639 // Update display while dozing
3640 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003641 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3642 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003643 // FIXME: eventthread only knows about the main display right now
3644 mEventThread->onScreenAcquired();
3645 resyncToHardwareVsync(true);
3646 }
3647 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3648 // Leave display going to doze
3649 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3650 disableHardwareVsync(true); // also cancels any in-progress resync
3651 // FIXME: eventthread only knows about the main display right now
3652 mEventThread->onScreenReleased();
3653 }
3654 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003655 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003656 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003657 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003658 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003659 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003660}
3661
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003662void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3663 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003664 SurfaceFlinger& mFlinger;
3665 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003666 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003667 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003668 MessageSetPowerMode(SurfaceFlinger& flinger,
3669 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3670 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003671 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003672 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003673 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003674 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003675 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003676 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003677 ALOGW("Attempt to set power mode = %d for virtual display",
3678 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003679 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003680 mFlinger.setPowerModeInternal(
3681 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003682 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003683 return true;
3684 }
3685 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003686 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003687 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003688}
3689
3690// ---------------------------------------------------------------------------
3691
Lloyd Pique755e3192018-01-31 16:46:15 -08003692status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3693 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003694 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003695
Mathias Agopianbd115332013-04-18 16:41:04 -07003696 IPCThreadState* ipc = IPCThreadState::self();
3697 const int pid = ipc->getCallingPid();
3698 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003699
Mathias Agopianbd115332013-04-18 16:41:04 -07003700 if ((uid != AID_SHELL) &&
3701 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003702 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003703 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003704 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003705 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003706 // (this would indicate SF is stuck, but we want to be able to
3707 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003708 status_t err = mStateLock.timedLock(s2ns(1));
3709 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003710 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003711 result.appendFormat(
3712 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3713 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003714 }
3715
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003716 bool dumpAll = true;
3717 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003718 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003719
3720 if (asProto) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003721 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviwa3d7bd32017-11-03 09:41:53 -07003722 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3723 dumpAll = false;
3724 }
3725
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003726 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003727 if ((index < numArgs) &&
3728 (args[index] == String16("--list"))) {
3729 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003730 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003731 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003732 }
3733
3734 if ((index < numArgs) &&
3735 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003736 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003737 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003738 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003739 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003740
3741 if ((index < numArgs) &&
3742 (args[index] == String16("--latency-clear"))) {
3743 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003744 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003745 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003746 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003747
3748 if ((index < numArgs) &&
3749 (args[index] == String16("--dispsync"))) {
3750 index++;
3751 mPrimaryDispSync.dump(result);
3752 dumpAll = false;
3753 }
Dan Stozab90cf072015-03-05 11:05:59 -08003754
3755 if ((index < numArgs) &&
3756 (args[index] == String16("--static-screen"))) {
3757 index++;
3758 dumpStaticScreenStats(result);
3759 dumpAll = false;
3760 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003761
3762 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003763 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003764 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003765 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003766 dumpAll = false;
3767 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003768
3769 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3770 index++;
3771 dumpWideColorInfo(result);
3772 dumpAll = false;
3773 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003774 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003775
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003776 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003777 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003778 }
3779
Mathias Agopian9795c422009-08-26 16:36:26 -07003780 if (locked) {
3781 mStateLock.unlock();
3782 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003783 }
3784 write(fd, result.string(), result.size());
3785 return NO_ERROR;
3786}
3787
Dan Stozac7014012014-02-14 15:03:43 -08003788void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3789 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003790{
Robert Carr2047fae2016-11-28 14:09:09 -08003791 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003792 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003793 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003794}
3795
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003796void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003797 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003798{
3799 String8 name;
3800 if (index < args.size()) {
3801 name = String8(args[index]);
3802 index++;
3803 }
3804
David Sodman105b7dc2017-11-04 20:28:14 -07003805 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003806 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003807 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003808
3809 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003810 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003811 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003812 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003813 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003814 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003815 }
Robert Carr2047fae2016-11-28 14:09:09 -08003816 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003817 }
3818}
3819
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003820void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003821 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003822{
3823 String8 name;
3824 if (index < args.size()) {
3825 name = String8(args[index]);
3826 index++;
3827 }
3828
Robert Carr2047fae2016-11-28 14:09:09 -08003829 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003830 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003831 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003832 }
Robert Carr2047fae2016-11-28 14:09:09 -08003833 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003834
Svetoslavd85084b2014-03-20 10:28:31 -07003835 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003836}
3837
Jamie Gennis6547ff42013-07-16 20:12:42 -07003838// This should only be called from the main thread. Otherwise it would need
3839// the lock and should use mCurrentState rather than mDrawingState.
3840void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003841 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003842 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003843 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003844
3845 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3846}
3847
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003848void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003849{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003850 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003851
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003852 if (isLayerTripleBufferingDisabled())
3853 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003854
3855 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003856 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003857 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003858 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003859 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3860 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003861 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003862}
3863
Dan Stozab90cf072015-03-05 11:05:59 -08003864void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3865{
3866 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003867 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3868 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003869 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003870 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003871 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3872 b + 1, bucketTimeSec, percent);
3873 }
David Sodman4a36e932017-11-07 14:29:47 -08003874 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003875 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003876 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003877 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08003878 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003879}
3880
Dan Stozae77c7662016-05-13 11:37:28 -07003881void SurfaceFlinger::recordBufferingStats(const char* layerName,
3882 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08003883 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
3884 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07003885 for (const auto& segment : history) {
3886 if (!segment.usedThirdBuffer) {
3887 stats.twoBufferTime += segment.totalTime;
3888 }
3889 if (segment.occupancyAverage < 1.0f) {
3890 stats.doubleBufferedTime += segment.totalTime;
3891 } else if (segment.occupancyAverage < 2.0f) {
3892 stats.tripleBufferedTime += segment.totalTime;
3893 }
3894 ++stats.numSegments;
3895 stats.totalTime += segment.totalTime;
3896 }
3897}
3898
Brian Andersond6927fb2016-07-23 23:37:30 -07003899void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3900 result.appendFormat("Layer frame timestamps:\n");
3901
3902 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3903 const size_t count = currentLayers.size();
3904 for (size_t i=0 ; i<count ; i++) {
3905 currentLayers[i]->dumpFrameEvents(result);
3906 }
3907}
3908
Dan Stozae77c7662016-05-13 11:37:28 -07003909void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3910 result.append("Buffering stats:\n");
3911 result.append(" [Layer name] <Active time> <Two buffer> "
3912 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08003913 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07003914 typedef std::tuple<std::string, float, float, float> BufferTuple;
3915 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08003916 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07003917 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08003918 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07003919 if (stats.numSegments == 0) {
3920 continue;
3921 }
3922 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3923 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3924 stats.totalTime;
3925 float doubleBufferRatio = static_cast<float>(
3926 stats.doubleBufferedTime) / stats.totalTime;
3927 float tripleBufferRatio = static_cast<float>(
3928 stats.tripleBufferedTime) / stats.totalTime;
3929 sorted.insert({activeTime, {name, twoBufferRatio,
3930 doubleBufferRatio, tripleBufferRatio}});
3931 }
3932 for (const auto& sortedPair : sorted) {
3933 float activeTime = sortedPair.first;
3934 const BufferTuple& values = sortedPair.second;
3935 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3936 std::get<0>(values).c_str(), activeTime,
3937 std::get<1>(values), std::get<2>(values),
3938 std::get<3>(values));
3939 }
3940 result.append("\n");
3941}
3942
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003943void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3944 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Romain Guy54f154a2017-10-24 21:40:32 +01003945 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003946
3947 // TODO: print out if wide-color mode is active or not
3948
3949 for (size_t d = 0; d < mDisplays.size(); d++) {
3950 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3951 int32_t hwcId = displayDevice->getHwcDisplayId();
3952 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3953 continue;
3954 }
3955
3956 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07003957 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003958 for (auto&& mode : modes) {
3959 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3960 }
3961
Peiyong Lina52f0292018-03-14 17:26:31 -07003962 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003963 result.appendFormat(" Current color mode: %s (%d)\n",
3964 decodeColorMode(currentMode).c_str(), currentMode);
3965 }
3966 result.append("\n");
3967}
3968
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003969LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07003970 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003971 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
3972 const State& state = useDrawing ? mDrawingState : mCurrentState;
3973 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07003974 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003975 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07003976 });
3977
3978 return layersProto;
3979}
3980
Mathias Agopian74d211a2013-04-22 16:55:35 +02003981void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3982 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003983{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003984 bool colorize = false;
3985 if (index < args.size()
3986 && (args[index] == String16("--color"))) {
3987 colorize = true;
3988 index++;
3989 }
3990
3991 Colorizer colorizer(colorize);
3992
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003993 // figure out if we're stuck somewhere
3994 const nsecs_t now = systemTime();
3995 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3996 const nsecs_t inTransaction(mDebugInTransaction);
3997 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3998 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3999
4000 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004001 * Dump library configuration.
4002 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004003
4004 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004005 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004006 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004007 appendSfConfigString(result);
4008 appendUiConfigString(result);
4009 appendGuiConfigString(result);
4010 result.append("\n");
4011
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004012 result.append("\nWide-Color information:\n");
4013 dumpWideColorInfo(result);
4014
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004015 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004016 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004017 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004018 result.append(SyncFeatures::getInstance().toString());
4019 result.append("\n");
4020
David Sodman105b7dc2017-11-04 20:28:14 -07004021 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004022
Andy McFadden41d67d72014-04-25 16:58:34 -07004023 colorizer.bold(result);
4024 result.append("DispSync configuration: ");
4025 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07004026 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004027 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08004028 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004029 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004030 result.append("\n");
4031
Dan Stozab90cf072015-03-05 11:05:59 -08004032 // Dump static screen stats
4033 result.append("\n");
4034 dumpStaticScreenStats(result);
4035 result.append("\n");
4036
Dan Stozae77c7662016-05-13 11:37:28 -07004037 dumpBufferingStats(result);
4038
Andy McFadden4803b742012-09-24 19:07:20 -07004039 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004040 * Dump the visible layer list
4041 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004042 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004043 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004044 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4045 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004046 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004047
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004048 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004049 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7794ec12018-03-14 13:28:39 -07004050 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004051
4052 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004053 * Dump Display state
4054 */
4055
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004056 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004057 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004058 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004059 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4060 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004061 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004062 }
4063
4064 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004065 * Dump SurfaceFlinger global state
4066 */
4067
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004068 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004069 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004070 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004071
Mathias Agopian888c8222012-08-04 21:10:38 -07004072 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004073 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004074
David Sodmanbc815282017-11-05 18:57:52 -08004075 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004076
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004077 if (hw) {
4078 hw->undefinedRegion.dump(result, "undefinedRegion");
4079 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4080 hw->getOrientation(), hw->isDisplayOn());
4081 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004082 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004083 " last eglSwapBuffers() time: %f us\n"
4084 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004085 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004086 " refresh-rate : %f fps\n"
4087 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004088 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004089 " gpu_to_cpu_unsupported : %d\n"
4090 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004091 mLastSwapBufferTime/1000.0,
4092 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004093 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004094 1e9 / activeConfig->getVsyncPeriod(),
4095 activeConfig->getDpiX(),
4096 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004097 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004098
Mathias Agopian74d211a2013-04-22 16:55:35 +02004099 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004100 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004101
Mathias Agopian74d211a2013-04-22 16:55:35 +02004102 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004103 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004104
4105 /*
4106 * VSYNC state
4107 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004108 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004109 result.append("\n");
4110
4111 /*
4112 * HWC layer minidump
4113 */
4114 for (size_t d = 0; d < mDisplays.size(); d++) {
4115 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4116 int32_t hwcId = displayDevice->getHwcDisplayId();
4117 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4118 continue;
4119 }
4120
4121 result.appendFormat("Display %d HWC layers:\n", hwcId);
4122 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004123 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004124 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004125 });
Dan Stozae22aec72016-08-01 13:20:59 -07004126 result.append("\n");
4127 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004128
4129 /*
4130 * Dump HWComposer state
4131 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004132 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004133 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004134 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004135 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004136 result.appendFormat(" h/w composer %s\n",
4137 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004138 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004139
4140 /*
4141 * Dump gralloc state
4142 */
4143 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4144 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004145
4146 /*
4147 * Dump VrFlinger state if in use.
4148 */
4149 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4150 result.append("VrFlinger state:\n");
4151 result.append(mVrFlinger->Dump().c_str());
4152 result.append("\n");
4153 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004154}
4155
Mathias Agopian13127d82013-03-05 17:47:11 -08004156const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004157SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004158 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004159 wp<IBinder> dpy;
4160 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4161 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4162 dpy = mDisplays.keyAt(i);
4163 break;
4164 }
4165 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004166 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004167 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4168 // Just use the primary display so we have something to return
4169 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4170 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004171 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004172}
4173
Keun young Park63f165f2012-08-31 10:53:36 -07004174bool SurfaceFlinger::startDdmConnection()
4175{
4176 void* libddmconnection_dso =
4177 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4178 if (!libddmconnection_dso) {
4179 return false;
4180 }
4181 void (*DdmConnection_start)(const char* name);
4182 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004183 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004184 if (!DdmConnection_start) {
4185 dlclose(libddmconnection_dso);
4186 return false;
4187 }
4188 (*DdmConnection_start)(getServiceName());
4189 return true;
4190}
4191
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004192status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004193 switch (code) {
4194 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004195 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004196 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004197 case CLEAR_ANIMATION_FRAME_STATS:
4198 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004199 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004200 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004201 case ENABLE_VSYNC_INJECTIONS:
4202 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004203 {
4204 // codes that require permission check
4205 IPCThreadState* ipc = IPCThreadState::self();
4206 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004207 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004208 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004209 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004210 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004211 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004212 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004213 break;
4214 }
Robert Carr1db73f62016-12-21 12:58:51 -08004215 /*
4216 * Calling setTransactionState is safe, because you need to have been
4217 * granted a reference to Client* and Handle* to do anything with it.
4218 *
4219 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4220 */
4221 case SET_TRANSACTION_STATE:
4222 case CREATE_SCOPED_CONNECTION:
4223 {
4224 return OK;
4225 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004226 case CAPTURE_SCREEN:
4227 {
4228 // codes that require permission check
4229 IPCThreadState* ipc = IPCThreadState::self();
4230 const int pid = ipc->getCallingPid();
4231 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004232 if ((uid != AID_GRAPHICS) &&
4233 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004234 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004235 return PERMISSION_DENIED;
4236 }
4237 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004238 }
chaviwa76b2712017-09-20 12:02:26 -07004239 case CAPTURE_LAYERS: {
4240 IPCThreadState* ipc = IPCThreadState::self();
4241 const int pid = ipc->getCallingPid();
4242 const int uid = ipc->getCallingUid();
4243 if ((uid != AID_GRAPHICS) &&
4244 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4245 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4246 return PERMISSION_DENIED;
4247 }
4248 break;
4249 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004250 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004251 return OK;
4252}
4253
4254status_t SurfaceFlinger::onTransact(
4255 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4256{
4257 status_t credentialCheck = CheckTransactCodeCredentials(code);
4258 if (credentialCheck != OK) {
4259 return credentialCheck;
4260 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004261
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004262 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4263 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004264 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004265 IPCThreadState* ipc = IPCThreadState::self();
4266 const int uid = ipc->getCallingUid();
4267 if (CC_UNLIKELY(uid != AID_SYSTEM
4268 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004269 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004270 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004271 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004272 return PERMISSION_DENIED;
4273 }
4274 int n;
4275 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004276 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004277 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004278 return NO_ERROR;
4279 case 1002: // SHOW_UPDATES
4280 n = data.readInt32();
4281 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004282 invalidateHwcGeometry();
4283 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004284 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004285 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004286 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004287 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004288 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004289 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004290 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004291 setTransactionFlags(
4292 eTransactionNeeded|
4293 eDisplayTransactionNeeded|
4294 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004295 return NO_ERROR;
4296 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004297 case 1006:{ // send empty update
4298 signalRefresh();
4299 return NO_ERROR;
4300 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004301 case 1008: // toggle use of hw composer
4302 n = data.readInt32();
4303 mDebugDisableHWC = n ? 1 : 0;
4304 invalidateHwcGeometry();
4305 repaintEverything();
4306 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004307 case 1009: // toggle use of transform hint
4308 n = data.readInt32();
4309 mDebugDisableTransformHint = n ? 1 : 0;
4310 invalidateHwcGeometry();
4311 repaintEverything();
4312 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004313 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004314 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004315 reply->writeInt32(0);
4316 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004317 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004318 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004319 return NO_ERROR;
4320 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004321 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004322 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004323 return NO_ERROR;
4324 }
4325 case 1014: {
4326 // daltonize
4327 n = data.readInt32();
4328 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004329 case 1:
4330 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4331 break;
4332 case 2:
4333 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4334 break;
4335 case 3:
4336 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4337 break;
4338 default:
4339 mDaltonizer.setType(ColorBlindnessType::None);
4340 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004341 }
4342 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004343 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004344 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004345 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004346 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004347 invalidateHwcGeometry();
4348 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004349 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004350 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004351 case 1015: {
4352 // apply a color matrix
4353 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004354 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004355 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004356 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004357 for (size_t j = 0; j < 4; j++) {
4358 mColorMatrix[i][j] = data.readFloat();
4359 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004360 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004361 } else {
4362 mColorMatrix = mat4();
4363 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004364
4365 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4366 // the division by w in the fragment shader
4367 float4 lastRow(transpose(mColorMatrix)[3]);
4368 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4369 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4370 }
4371
Alan Viverette9c5a3332013-09-12 20:04:35 -07004372 invalidateHwcGeometry();
4373 repaintEverything();
4374 return NO_ERROR;
4375 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004376 // This is an experimental interface
4377 // Needs to be shifted to proper binder interface when we productize
4378 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004379 n = data.readInt32();
4380 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004381 return NO_ERROR;
4382 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004383 case 1017: {
4384 n = data.readInt32();
4385 mForceFullDamage = static_cast<bool>(n);
4386 return NO_ERROR;
4387 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004388 case 1018: { // Modify Choreographer's phase offset
4389 n = data.readInt32();
4390 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4391 return NO_ERROR;
4392 }
4393 case 1019: { // Modify SurfaceFlinger's phase offset
4394 n = data.readInt32();
4395 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4396 return NO_ERROR;
4397 }
Irvel468051e2016-06-13 16:44:44 -07004398 case 1020: { // Layer updates interceptor
4399 n = data.readInt32();
4400 if (n) {
4401 ALOGV("Interceptor enabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004402 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004403 }
4404 else{
4405 ALOGV("Interceptor disabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004406 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004407 }
4408 return NO_ERROR;
4409 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004410 case 1021: { // Disable HWC virtual displays
4411 n = data.readInt32();
4412 mUseHwcVirtualDisplays = !n;
4413 return NO_ERROR;
4414 }
Romain Guy0147a172017-06-01 13:53:56 -07004415 case 1022: { // Set saturation boost
4416 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4417
4418 invalidateHwcGeometry();
4419 repaintEverything();
4420 return NO_ERROR;
4421 }
Romain Guy54f154a2017-10-24 21:40:32 +01004422 case 1023: { // Set native mode
4423 mForceNativeColorMode = data.readInt32() == 1;
4424
4425 invalidateHwcGeometry();
4426 repaintEverything();
4427 return NO_ERROR;
4428 }
4429 case 1024: { // Is wide color gamut rendering/color management supported?
4430 reply->writeBool(hasWideColorDisplay);
4431 return NO_ERROR;
4432 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004433 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004434 n = data.readInt32();
4435 if (n) {
4436 ALOGV("LayerTracing enabled");
4437 mTracing.enable();
4438 doTracing("tracing.enable");
4439 reply->writeInt32(NO_ERROR);
4440 } else {
4441 ALOGV("LayerTracing disabled");
4442 status_t err = mTracing.disable();
4443 reply->writeInt32(err);
4444 }
4445 return NO_ERROR;
4446 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004447 case 1026: { // Get layer tracing status
4448 reply->writeBool(mTracing.isEnabled());
4449 return NO_ERROR;
4450 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004451 }
4452 }
4453 return err;
4454}
4455
Steven Thomas6d8110b2017-08-31 18:24:21 -07004456void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004457 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004458 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004459}
4460
Steven Thomas6d8110b2017-08-31 18:24:21 -07004461void SurfaceFlinger::repaintEverything() {
4462 ConditionalLock _l(mStateLock,
4463 std::this_thread::get_id() != mMainThreadId);
4464 repaintEverythingLocked();
4465}
4466
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004467// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4468class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004469public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004470 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4471 ~WindowDisconnector() {
4472 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004473 }
4474
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004475private:
4476 ANativeWindow* mWindow;
4477 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004478};
4479
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004480status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4481 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4482 int32_t minLayerZ, int32_t maxLayerZ,
4483 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004484 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004485 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004486
chaviwa76b2712017-09-20 12:02:26 -07004487 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4488
4489 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004490 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4491
chaviwa76b2712017-09-20 12:02:26 -07004492 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4493
4494 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4495 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004496 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004497}
4498
4499status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004500 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004501 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004502 ATRACE_CALL();
4503
4504 class LayerRenderArea : public RenderArea {
4505 public:
Robert Carr578038f2018-03-09 12:25:24 -08004506 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4507 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
4508 : RenderArea(reqHeight, reqWidth),
4509 mLayer(layer),
4510 mCrop(crop),
4511 mFlinger(flinger),
4512 mChildrenOnly(childrenOnly) {}
chaviwa76b2712017-09-20 12:02:26 -07004513 Rect getBounds() const override {
4514 const Layer::State& layerState(mLayer->getDrawingState());
4515 return Rect(layerState.active.w, layerState.active.h);
4516 }
4517 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4518 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4519 bool isSecure() const override { return false; }
4520 bool needsFiltering() const override { return false; }
Robert Carr578038f2018-03-09 12:25:24 -08004521 const Transform& getTransform() const { return mTransform; }
4522
4523 class ReparentForDrawing {
4524 public:
4525 const sp<Layer>& oldParent;
4526 const sp<Layer>& newParent;
4527
4528 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4529 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004530 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004531 }
Robert Carr15eae092018-03-23 13:43:53 -07004532 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004533 };
4534
4535 void render(std::function<void()> drawLayers) override {
4536 if (!mChildrenOnly) {
4537 mTransform = mLayer->getTransform().inverse();
4538 drawLayers();
4539 } else {
4540 Rect bounds = getBounds();
4541 screenshotParentLayer =
4542 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4543 bounds.getWidth(), bounds.getHeight(), 0);
4544
4545 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4546 drawLayers();
4547 }
4548 }
chaviwa76b2712017-09-20 12:02:26 -07004549
chaviw7206d492017-11-10 16:16:12 -08004550 Rect getSourceCrop() const override {
4551 if (mCrop.isEmpty()) {
4552 return getBounds();
4553 } else {
4554 return mCrop;
4555 }
4556 }
chaviwa76b2712017-09-20 12:02:26 -07004557 bool getWideColorSupport() const override { return false; }
Peiyong Lina52f0292018-03-14 17:26:31 -07004558 ColorMode getActiveColorMode() const override { return ColorMode::NATIVE; }
chaviwa76b2712017-09-20 12:02:26 -07004559
4560 private:
chaviw7206d492017-11-10 16:16:12 -08004561 const sp<Layer> mLayer;
4562 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004563
4564 // In the "childrenOnly" case we reparent the children to a screenshot
4565 // layer which has no properties set and which does not draw.
4566 sp<ContainerLayer> screenshotParentLayer;
4567 Transform mTransform;
4568
4569 SurfaceFlinger* mFlinger;
4570 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004571 };
4572
4573 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4574 auto parent = layerHandle->owner.promote();
4575
chaviw7206d492017-11-10 16:16:12 -08004576 if (parent == nullptr || parent->isPendingRemoval()) {
4577 ALOGE("captureLayers called with a removed parent");
4578 return NAME_NOT_FOUND;
4579 }
4580
Robert Carr578038f2018-03-09 12:25:24 -08004581 const int uid = IPCThreadState::self()->getCallingUid();
4582 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4583 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4584 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4585 return PERMISSION_DENIED;
4586 }
4587
chaviw7206d492017-11-10 16:16:12 -08004588 Rect crop(sourceCrop);
4589 if (sourceCrop.width() <= 0) {
4590 crop.left = 0;
4591 crop.right = parent->getCurrentState().active.w;
4592 }
4593
4594 if (sourceCrop.height() <= 0) {
4595 crop.top = 0;
4596 crop.bottom = parent->getCurrentState().active.h;
4597 }
4598
4599 int32_t reqWidth = crop.width() * frameScale;
4600 int32_t reqHeight = crop.height() * frameScale;
4601
Robert Carr578038f2018-03-09 12:25:24 -08004602 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004603
Robert Carr578038f2018-03-09 12:25:24 -08004604 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004605 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4606 if (!layer->isVisible()) {
4607 return;
Robert Carr578038f2018-03-09 12:25:24 -08004608 } else if (childrenOnly && layer == parent.get()) {
4609 return;
chaviwa76b2712017-09-20 12:02:26 -07004610 }
4611 visitor(layer);
4612 });
4613 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004614 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004615}
4616
4617status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4618 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004619 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004620 bool useIdentityTransform) {
4621 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004622
chaviwa76b2712017-09-20 12:02:26 -07004623 renderArea.updateDimensions();
4624
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004625 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4626 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4627 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4628 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004629
4630 // This mutex protects syncFd and captureResult for communication of the return values from the
4631 // main thread back to this Binder thread
4632 std::mutex captureMutex;
4633 std::condition_variable captureCondition;
4634 std::unique_lock<std::mutex> captureLock(captureMutex);
4635 int syncFd = -1;
4636 std::optional<status_t> captureResult;
4637
Robert Carr03480e22018-01-04 16:02:06 -08004638 const int uid = IPCThreadState::self()->getCallingUid();
4639 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4640
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004641 sp<LambdaMessage> message = new LambdaMessage([&]() {
4642 // If there is a refresh pending, bug out early and tell the binder thread to try again
4643 // after the refresh.
4644 if (mRefreshPending) {
4645 ATRACE_NAME("Skipping screenshot for now");
4646 std::unique_lock<std::mutex> captureLock(captureMutex);
4647 captureResult = std::make_optional<status_t>(EAGAIN);
4648 captureCondition.notify_one();
4649 return;
4650 }
4651
4652 status_t result = NO_ERROR;
4653 int fd = -1;
4654 {
4655 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004656 renderArea.render([&]() {
4657 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4658 useIdentityTransform, forSystem, &fd);
4659 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004660 }
4661
4662 {
4663 std::unique_lock<std::mutex> captureLock(captureMutex);
4664 syncFd = fd;
4665 captureResult = std::make_optional<status_t>(result);
4666 captureCondition.notify_one();
4667 }
4668 });
4669
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004670 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004671 if (result == NO_ERROR) {
4672 captureCondition.wait(captureLock, [&]() { return captureResult; });
4673 while (*captureResult == EAGAIN) {
4674 captureResult.reset();
4675 result = postMessageAsync(message);
4676 if (result != NO_ERROR) {
4677 return result;
4678 }
4679 captureCondition.wait(captureLock, [&]() { return captureResult; });
4680 }
4681 result = *captureResult;
4682 }
4683
4684 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004685 sync_wait(syncFd, -1);
4686 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004687 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004688
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004689 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004690}
4691
chaviwa76b2712017-09-20 12:02:26 -07004692void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4693 TraverseLayersFunction traverseLayers, bool yswap,
4694 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004695 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004696
Lloyd Pique144e1162017-12-20 16:44:52 -08004697 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004698
4699 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004700 const auto raWidth = renderArea.getWidth();
4701 const auto raHeight = renderArea.getHeight();
4702
4703 const auto reqWidth = renderArea.getReqWidth();
4704 const auto reqHeight = renderArea.getReqHeight();
4705 Rect sourceCrop = renderArea.getSourceCrop();
4706
4707 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4708 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004709
Dan Stozac1879002014-05-22 15:59:05 -07004710 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004711 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004712 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004713 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004714 }
4715
4716 // ensure that sourceCrop is inside screen
4717 if (sourceCrop.left < 0) {
4718 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4719 }
chaviwa76b2712017-09-20 12:02:26 -07004720 if (sourceCrop.right > raWidth) {
4721 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004722 }
4723 if (sourceCrop.top < 0) {
4724 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4725 }
chaviwa76b2712017-09-20 12:02:26 -07004726 if (sourceCrop.bottom > raHeight) {
4727 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004728 }
4729
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004730 android_dataspace outputDataspace = HAL_DATASPACE_UNKNOWN;
Chia-I Wu9a48a8c2018-02-20 14:27:30 -08004731 if (renderArea.getWideColorSupport() &&
Peiyong Lina52f0292018-03-14 17:26:31 -07004732 renderArea.getActiveColorMode() == ColorMode::DISPLAY_P3) {
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004733 outputDataspace = HAL_DATASPACE_DISPLAY_P3;
4734 }
4735 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Romain Guy88d37dd2017-05-26 17:57:05 -07004736
Mathias Agopian180f10d2013-04-10 22:55:41 -07004737 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004738 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004739
4740 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004741 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4742 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004743 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004744
4745 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004746 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004747
chaviwa76b2712017-09-20 12:02:26 -07004748 traverseLayers([&](Layer* layer) {
4749 if (filtering) layer->setFiltering(true);
4750 layer->draw(renderArea, useIdentityTransform);
4751 if (filtering) layer->setFiltering(false);
4752 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004753}
4754
chaviwa76b2712017-09-20 12:02:26 -07004755status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4756 TraverseLayersFunction traverseLayers,
4757 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004758 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08004759 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07004760 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004761 ATRACE_CALL();
4762
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004763 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004764
4765 traverseLayers([&](Layer* layer) {
4766 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4767 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004768
Robert Carr03480e22018-01-04 16:02:06 -08004769 // We allow the system server to take screenshots of secure layers for
4770 // use in situations like the Screen-rotation animation and place
4771 // the impetus on WindowManager to not persist them.
4772 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004773 ALOGW("FB is protected: PERMISSION_DENIED");
4774 return PERMISSION_DENIED;
4775 }
4776
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004777 // this binds the given EGLImage as a framebuffer for the
4778 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08004779 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08004780 if (bufferBond.getStatus() != NO_ERROR) {
4781 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004782 return INVALID_OPERATION;
4783 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004784
Dan Stozaabcda352017-06-01 14:37:39 -07004785 // this will in fact render into our dequeued buffer
4786 // via an FBO, which means we didn't have to create
4787 // an EGLSurface and therefore we're not
4788 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004789 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004790
Dan Stozaabcda352017-06-01 14:37:39 -07004791 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08004792 getRenderEngine().finish();
4793 *outSyncFd = -1;
4794
chaviwa76b2712017-09-20 12:02:26 -07004795 const auto reqWidth = renderArea.getReqWidth();
4796 const auto reqHeight = renderArea.getReqHeight();
4797
Dan Stozaabcda352017-06-01 14:37:39 -07004798 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4799 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004800 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004801 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08004802 } else {
4803 base::unique_fd syncFd = getRenderEngine().flush();
4804 if (syncFd < 0) {
4805 getRenderEngine().finish();
4806 }
4807 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07004808 }
4809
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004810 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004811}
4812
Mathias Agopiand5556842013-09-19 17:08:37 -07004813void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07004814 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004815 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004816 for (size_t y = 0; y < h; y++) {
4817 uint32_t const* p = (uint32_t const*)vaddr + y * s;
4818 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004819 if (p[x] != 0xFF000000) return;
4820 }
4821 }
chaviwa76b2712017-09-20 12:02:26 -07004822 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07004823
Robert Carr2047fae2016-11-28 14:09:09 -08004824 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07004825 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004826 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07004827 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4828 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
4829 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
4830 static_cast<float>(state.color.a));
4831 i++;
4832 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07004833 }
4834}
4835
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004836// ---------------------------------------------------------------------------
4837
Dan Stoza412903f2017-04-27 13:42:17 -07004838void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4839 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004840}
4841
Dan Stoza412903f2017-04-27 13:42:17 -07004842void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4843 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004844}
4845
chaviwa76b2712017-09-20 12:02:26 -07004846void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
4847 int32_t maxLayerZ,
4848 const LayerVector::Visitor& visitor) {
4849 // We loop through the first level of layers without traversing,
4850 // as we need to interpret min/max layer Z in the top level Z space.
4851 for (const auto& layer : mDrawingState.layersSortedByZ) {
4852 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4853 continue;
4854 }
4855 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08004856 // relative layers are traversed in Layer::traverseInZOrder
4857 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07004858 continue;
4859 }
4860 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01004861 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4862 return;
4863 }
chaviwa76b2712017-09-20 12:02:26 -07004864 if (!layer->isVisible()) {
4865 return;
4866 }
4867 visitor(layer);
4868 });
4869 }
4870}
4871
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004872}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004873
4874
4875#if defined(__gl_h_)
4876#error "don't include gl/gl.h in this file"
4877#endif
4878
4879#if defined(__gl2_h_)
4880#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08004881#endif