blob: 4c695c44079109b7f39cb6a38be5e379f7dadbfc [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;
Peiyong Linfd997e02018-03-28 15:29:00 -0700107using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700108using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700109using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700110using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900111
Steven Thomasb02664d2017-07-26 18:48:28 -0700112namespace {
113class ConditionalLock {
114public:
115 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
116 if (lock) {
117 mMutex.lock();
118 }
119 }
120 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
121private:
122 Mutex& mMutex;
123 bool mLocked;
124};
125} // namespace anonymous
126
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800127// ---------------------------------------------------------------------------
128
Mathias Agopian99b49842011-06-27 16:05:52 -0700129const String16 sHardwareTest("android.permission.HARDWARE_TEST");
130const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
131const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
132const String16 sDump("android.permission.DUMP");
133
134// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800135int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
136int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700137int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700138bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800139uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800140bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800141bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800142int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800143// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600144bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700145
Kalle Raitaa099a242017-01-11 11:17:29 -0800146
147std::string getHwcServiceName() {
148 char value[PROPERTY_VALUE_MAX] = {};
149 property_get("debug.sf.hwc_service_name", value, "default");
150 ALOGI("Using HWComposer service: '%s'", value);
151 return std::string(value);
152}
153
154bool useTrebleTestingOverride() {
155 char value[PROPERTY_VALUE_MAX] = {};
156 property_get("debug.sf.treble_testing_override", value, "false");
157 ALOGI("Treble testing override: '%s'", value);
158 return std::string(value) == "true";
159}
160
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800161std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
162 switch(displayColorSetting) {
163 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700164 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800165 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700166 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800167 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700168 return std::string("Enhanced");
169 default:
170 return std::string("Unknown ") +
171 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800172 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800173}
174
Lloyd Pique09594832018-01-22 17:48:03 -0800175NativeWindowSurface::~NativeWindowSurface() = default;
176
177namespace impl {
178
179class NativeWindowSurface final : public android::NativeWindowSurface {
180public:
181 static std::unique_ptr<android::NativeWindowSurface> create(
182 const sp<IGraphicBufferProducer>& producer) {
183 return std::make_unique<NativeWindowSurface>(producer);
184 }
185
186 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
187 : surface(new Surface(producer, false)) {}
188
189 ~NativeWindowSurface() override = default;
190
191private:
192 sp<ANativeWindow> getNativeWindow() const override { return surface; }
193
194 void preallocateBuffers() override { surface->allocateBuffers(); }
195
196 sp<Surface> surface;
197};
198
199} // namespace impl
200
David Sodmanbc815282017-11-05 18:57:52 -0800201SurfaceFlingerBE::SurfaceFlingerBE()
202 : mHwcServiceName(getHwcServiceName()),
203 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800204 mFrameBuckets(),
205 mTotalTime(0),
206 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800207 mComposerSequenceId(0) {
208}
209
Lloyd Pique2d3ee6d2018-01-17 13:42:24 -0800210SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800211 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800212 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700213 mTransactionPending(false),
214 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700215 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700216 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700217 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800218 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800219 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800220 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800221 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800222 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800223 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700224 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700225 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700226 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700227 mDebugInSwapBuffers(0),
228 mLastSwapBufferTime(0),
229 mDebugInTransaction(0),
230 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700231 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700232 mForceFullDamage(false),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000233 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700234 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700235 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800236 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800237 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700238 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800239 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique09594832018-01-22 17:48:03 -0800240 mCreateBufferQueue(&BufferQueue::createBufferQueue),
241 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Pique2d3ee6d2018-01-17 13:42:24 -0800242
243SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800244 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800245
246 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
247 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
248
249 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
250 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
251
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800252 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
253 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800254
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700255 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
256 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
257
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700258 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
259 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
260
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800261 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
262 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
263
Steven Thomas050b2c82017-03-06 11:45:16 -0800264 // Vr flinger is only enabled on Daydream ready devices.
265 useVrFlinger = getBool< ISurfaceFlingerConfigs,
266 &ISurfaceFlingerConfigs::useVrFlinger>(false);
267
Fabien Sanglard1971b632017-03-10 14:50:03 -0800268 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
269 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
270
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600271 hasWideColorDisplay =
272 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
273
David Sodman99974d22017-11-28 12:04:33 -0800274 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700275
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800276 // debugging stuff...
277 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700278
Mathias Agopianb4b17302013-03-20 18:36:41 -0700279 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700280 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700281
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800282 property_get("debug.sf.showupdates", value, "0");
283 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700284
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700285 property_get("debug.sf.ddms", value, "0");
286 mDebugDDMS = atoi(value);
287 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700288 if (!startDdmConnection()) {
289 // start failed, and DDMS debugging not enabled
290 mDebugDDMS = 0;
291 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700292 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700293 ALOGI_IF(mDebugRegion, "showupdates enabled");
294 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700295
296 property_get("debug.sf.disable_backpressure", value, "0");
297 mPropagateBackpressure = !atoi(value);
298 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700299
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800300 property_get("debug.sf.enable_hwc_vds", value, "0");
301 mUseHwcVirtualDisplays = atoi(value);
302 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800303
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800304 property_get("ro.sf.disable_triple_buffer", value, "1");
305 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800306 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700307
Yiwei Zhang243b3782018-05-15 17:40:04 -0700308 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700309 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
310 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
311
Dan Stoza2713c302018-03-28 17:07:36 -0700312 property_get("debug.sf.early_phase_offset_ns", value, "0");
313 const int earlyWakeupOffsetOffsetNs = atoi(value);
314 ALOGI_IF(earlyWakeupOffsetOffsetNs != 0, "Enabling separate early offset");
315 mVsyncModulator.setPhaseOffsets(sfVsyncPhaseOffsetNs - earlyWakeupOffsetOffsetNs,
316 sfVsyncPhaseOffsetNs);
317
Romain Guy11d63f42017-07-20 12:47:14 -0700318 // We should be reading 'persist.sys.sf.color_saturation' here
319 // but since /data may be encrypted, we need to wait until after vold
320 // comes online to attempt to read the property. The property is
321 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800322
323 if (useTrebleTestingOverride()) {
324 // Without the override SurfaceFlinger cannot connect to HIDL
325 // services that are not listed in the manifests. Considered
326 // deriving the setting from the set service name, but it
327 // would be brittle if the name that's not 'default' is used
328 // for production purposes later on.
329 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
330 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800331}
332
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800333void SurfaceFlinger::onFirstRef()
334{
Lloyd Pique9123ae52018-01-22 17:14:00 -0800335 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800336}
337
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800338SurfaceFlinger::~SurfaceFlinger()
339{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800340}
341
Dan Stozac7014012014-02-14 15:03:43 -0800342void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800343{
344 // the window manager died on us. prepare its eulogy.
345
Andy McFadden13a082e2012-08-24 10:16:42 -0700346 // restore initial conditions (default device unblank, etc)
347 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800348
349 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700350 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800351}
352
Robert Carr1db73f62016-12-21 12:58:51 -0800353static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700354 status_t err = client->initCheck();
355 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800356 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800357 }
Robert Carr1db73f62016-12-21 12:58:51 -0800358 return nullptr;
359}
360
361sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
362 return initClient(new Client(this));
363}
364
365sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
366 const sp<IGraphicBufferProducer>& gbp) {
367 if (authenticateSurfaceTexture(gbp) == false) {
368 return nullptr;
369 }
370 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
371 if (layer == nullptr) {
372 return nullptr;
373 }
374
375 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800376}
377
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700378sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
379 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700380{
381 class DisplayToken : public BBinder {
382 sp<SurfaceFlinger> flinger;
383 virtual ~DisplayToken() {
384 // no more references, this display must be terminated
385 Mutex::Autolock _l(flinger->mStateLock);
386 flinger->mCurrentState.displays.removeItem(this);
387 flinger->setTransactionFlags(eDisplayTransactionNeeded);
388 }
389 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700390 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700391 : flinger(flinger) {
392 }
393 };
394
395 sp<BBinder> token = new DisplayToken(this);
396
397 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700398 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700399 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700400 mCurrentState.displays.add(token, info);
Lloyd Pique4d234852018-01-22 17:21:36 -0800401 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700402 return token;
403}
404
Jesse Hall6c913be2013-08-08 12:15:49 -0700405void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
406 Mutex::Autolock _l(mStateLock);
407
408 ssize_t idx = mCurrentState.displays.indexOfKey(display);
409 if (idx < 0) {
410 ALOGW("destroyDisplay: invalid display token");
411 return;
412 }
413
414 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
415 if (!info.isVirtualDisplay()) {
416 ALOGE("destroyDisplay called for non-virtual display");
417 return;
418 }
Lloyd Pique4d234852018-01-22 17:21:36 -0800419 mInterceptor->saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700420 mCurrentState.displays.removeItemsAt(idx);
421 setTransactionFlags(eDisplayTransactionNeeded);
422}
423
Mathias Agopiane57f2922012-08-09 16:29:12 -0700424sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700425 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700426 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800427 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700428 }
Jesse Hall692c7232012-11-08 15:41:56 -0800429 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700430}
431
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800432void SurfaceFlinger::bootFinished()
433{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700434 if (mStartPropertySetThread->join() != NO_ERROR) {
435 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800436 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800437 const nsecs_t now = systemTime();
438 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000439 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700440
441 // wait patiently for the window manager death
442 const String16 name("window");
443 sp<IBinder> window(defaultServiceManager()->getService(name));
444 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700445 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700446 }
447
Steven Thomas050b2c82017-03-06 11:45:16 -0800448 if (mVrFlinger) {
449 mVrFlinger->OnBootFinished();
450 }
451
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700452 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700453 // formerly we would just kill the process, but we now ask it to exit so it
454 // can choose where to stop the animation.
455 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700456
457 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
458 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
459 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700460
Thierry Strudel2924d012017-08-14 15:19:37 -0700461 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700462 readPersistentProperties();
463 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700464 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800465}
466
Mathias Agopian3f844832013-08-07 21:24:32 -0700467void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700468 class MessageDestroyGLTexture : public MessageBase {
Lloyd Pique144e1162017-12-20 16:44:52 -0800469 RE::RenderEngine& engine;
Mathias Agopian3f844832013-08-07 21:24:32 -0700470 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700471 public:
Lloyd Pique144e1162017-12-20 16:44:52 -0800472 MessageDestroyGLTexture(RE::RenderEngine& engine, uint32_t texture)
473 : engine(engine), texture(texture) {}
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700474 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700475 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700476 return true;
477 }
478 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700479 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700480}
481
Lloyd Piquee83f9312018-02-01 12:53:17 -0800482class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700483public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700484 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000485 const char* name) :
486 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700487 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700488 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000489 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
490 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700491 mDispSync(dispSync),
492 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700493 mVsyncMutex(),
494 mPhaseOffset(phaseOffset),
495 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700496
Lloyd Piquee83f9312018-02-01 12:53:17 -0800497 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700498
Lloyd Piquee83f9312018-02-01 12:53:17 -0800499 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700500 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700501 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000502 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700503 static_cast<DispSync::Callback*>(this));
504 if (err != NO_ERROR) {
505 ALOGE("error registering vsync callback: %s (%d)",
506 strerror(-err), err);
507 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700508 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700509 } else {
510 status_t err = mDispSync->removeEventListener(
511 static_cast<DispSync::Callback*>(this));
512 if (err != NO_ERROR) {
513 ALOGE("error unregistering vsync callback: %s (%d)",
514 strerror(-err), err);
515 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700516 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700517 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700518 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700519 }
520
Lloyd Piquee83f9312018-02-01 12:53:17 -0800521 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700522 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700523 mCallback = callback;
524 }
525
Lloyd Piquee83f9312018-02-01 12:53:17 -0800526 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700527 Mutex::Autolock lock(mVsyncMutex);
528
529 // Normalize phaseOffset to [0, period)
530 auto period = mDispSync->getPeriod();
531 phaseOffset %= period;
532 if (phaseOffset < 0) {
533 // If we're here, then phaseOffset is in (-period, 0). After this
534 // operation, it will be in (0, period)
535 phaseOffset += period;
536 }
537 mPhaseOffset = phaseOffset;
538
539 // If we're not enabled, we don't need to mess with the listeners
540 if (!mEnabled) {
541 return;
542 }
543
Dan Stoza2713c302018-03-28 17:07:36 -0700544 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
545 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700546 if (err != NO_ERROR) {
Dan Stoza2713c302018-03-28 17:07:36 -0700547 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700548 strerror(-err), err);
549 }
550 }
551
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700552private:
553 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800554 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700555 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700556 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700557 callback = mCallback;
558
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700559 if (mTraceVsync) {
560 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700561 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700562 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700563 }
564
Peiyong Lin566a3b42018-01-09 18:22:43 -0800565 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700566 callback->onVSyncEvent(when);
567 }
568 }
569
Tim Murray4a4e4a22016-04-19 16:29:23 +0000570 const char* const mName;
571
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700572 int mValue;
573
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700574 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700575 const String8 mVsyncOnLabel;
576 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700577
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700578 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700579
580 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800581 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700582
583 Mutex mVsyncMutex; // Protects the following
584 nsecs_t mPhaseOffset;
585 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700586};
587
Lloyd Piquee83f9312018-02-01 12:53:17 -0800588class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700589public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800590 InjectVSyncSource() = default;
591 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700592
Lloyd Piquee83f9312018-02-01 12:53:17 -0800593 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700594 std::lock_guard<std::mutex> lock(mCallbackMutex);
595 mCallback = callback;
596 }
597
Lloyd Piquee83f9312018-02-01 12:53:17 -0800598 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700599 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700600 if (mCallback) {
601 mCallback->onVSyncEvent(when);
602 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700603 }
604
Lloyd Piquee83f9312018-02-01 12:53:17 -0800605 void setVSyncEnabled(bool) override {}
606 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700607
608private:
609 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800610 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700611};
612
Wei Wangf9b05ee2017-07-19 20:59:39 -0700613// Do not call property_set on main thread which will be blocked by init
614// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700615void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700616 ALOGI( "SurfaceFlinger's main thread ready to run. "
617 "Initializing graphics H/W...");
618
Thierry Strudel2924d012017-08-14 15:19:37 -0700619 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900620
Steven Thomasb02664d2017-07-26 18:48:28 -0700621 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800622
Steven Thomasb02664d2017-07-26 18:48:28 -0700623 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800624 mEventThreadSource =
625 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
626 true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800627 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
628 [this]() { resyncWithRateLimit(); },
629 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800630 "appEventThread");
631 mSfEventThreadSource =
632 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
633 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800634
Lloyd Pique24b0a482018-03-09 18:52:26 -0800635 mSFEventThread =
636 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
637 [this]() { resyncWithRateLimit(); },
638 [this](nsecs_t timestamp) {
639 mInterceptor->saveVSyncEvent(timestamp);
640 },
641 "sfEventThread");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800642 mEventQueue->setEventThread(mSFEventThread.get());
Dan Stoza2713c302018-03-28 17:07:36 -0700643 mVsyncModulator.setEventThread(mSFEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800644
Steven Thomasb02664d2017-07-26 18:48:28 -0700645 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800646 getBE().mRenderEngine =
647 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
648 hasWideColorDisplay
649 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
650 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800651 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700652
653 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
654 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800655 getBE().mHwc.reset(
656 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700657 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800658 // Process any initial hotplug and resulting display changes.
659 processDisplayHotplugEventsLocked();
660 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
661 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800662
Lloyd Piquefcd86612017-12-14 17:15:36 -0800663 // make the default display GLContext current so that we can create textures
664 // when creating Layers (which may happens before we render something)
665 getDefaultDisplayDeviceLocked()->makeCurrent();
666
Steven Thomas050b2c82017-03-06 11:45:16 -0800667 if (useVrFlinger) {
668 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700669 // This callback is called from the vr flinger dispatch thread. We
670 // need to call signalTransaction(), which requires holding
671 // mStateLock when we're not on the main thread. Acquiring
672 // mStateLock from the vr flinger dispatch thread might trigger a
673 // deadlock in surface flinger (see b/66916578), so post a message
674 // to be handled on the main thread instead.
675 sp<LambdaMessage> message = new LambdaMessage([=]() {
676 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
677 mVrFlingerRequestsDisplay = requestDisplay;
678 signalTransaction();
679 });
680 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800681 };
David Sodman105b7dc2017-11-04 20:28:14 -0700682 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
683 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800684 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800685 if (!mVrFlinger) {
686 ALOGE("Failed to start vrflinger");
687 }
688 }
689
Lloyd Pique0c3a8832018-01-22 17:31:47 -0800690 mEventControlThread = std::make_unique<impl::EventControlThread>(
691 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700692
Mathias Agopian92a979a2012-08-02 18:32:23 -0700693 // initialize our drawing state
694 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700695
Andy McFadden13a082e2012-08-24 10:16:42 -0700696 // set initial conditions (e.g. unblank default device)
697 initializeDisplays();
698
David Sodmanbc815282017-11-05 18:57:52 -0800699 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700700
Wei Wangf9b05ee2017-07-19 20:59:39 -0700701 // Inform native graphics APIs whether the present timestamp is supported:
702 if (getHwComposer().hasCapability(
703 HWC2::Capability::PresentFenceIsNotReliable)) {
704 mStartPropertySetThread = new StartPropertySetThread(false);
705 } else {
706 mStartPropertySetThread = new StartPropertySetThread(true);
707 }
708
709 if (mStartPropertySetThread->Start() != NO_ERROR) {
710 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800711 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800712
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800713 mLegacySrgbSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(HWC_DISPLAY_PRIMARY,
714 Dataspace::SRGB_LINEAR);
715
Dan Stoza9e56aa02015-11-02 13:00:03 -0800716 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700717}
718
Romain Guy11d63f42017-07-20 12:47:14 -0700719void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700720 Mutex::Autolock _l(mStateLock);
721
Romain Guy11d63f42017-07-20 12:47:14 -0700722 char value[PROPERTY_VALUE_MAX];
723
724 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800725 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700726 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800727 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100728
729 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700730 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700731}
732
Mathias Agopiana67e4182012-06-19 17:26:12 -0700733void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800734 // Start boot animation service by setting a property mailbox
735 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700736 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800737 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700738 if (mStartPropertySetThread->join() != NO_ERROR) {
739 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800740 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700741}
742
Mathias Agopian875d8e12013-06-07 15:35:48 -0700743size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800744 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700745}
746
Mathias Agopian875d8e12013-06-07 15:35:48 -0700747size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800748 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700749}
750
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800751// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800752
Jamie Gennis582270d2011-08-17 18:19:00 -0700753bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800754 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800755 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800756 return authenticateSurfaceTextureLocked(bufferProducer);
757}
758
759bool SurfaceFlinger::authenticateSurfaceTextureLocked(
760 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800761 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800762 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800763}
764
Brian Anderson6b376712017-04-04 10:51:39 -0700765status_t SurfaceFlinger::getSupportedFrameTimestamps(
766 std::vector<FrameEvent>* outSupported) const {
767 *outSupported = {
768 FrameEvent::REQUESTED_PRESENT,
769 FrameEvent::ACQUIRE,
770 FrameEvent::LATCH,
771 FrameEvent::FIRST_REFRESH_START,
772 FrameEvent::LAST_REFRESH_START,
773 FrameEvent::GPU_COMPOSITION_DONE,
774 FrameEvent::DEQUEUE_READY,
775 FrameEvent::RELEASE,
776 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700777 ConditionalLock _l(mStateLock,
778 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700779 if (!getHwComposer().hasCapability(
780 HWC2::Capability::PresentFenceIsNotReliable)) {
781 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
782 }
783 return NO_ERROR;
784}
785
Dan Stoza7f7da322014-05-02 15:26:25 -0700786status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
787 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800788 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700789 return BAD_VALUE;
790 }
791
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500792 if (!display.get())
793 return NAME_NOT_FOUND;
794
Jesse Hall692c7232012-11-08 15:41:56 -0800795 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700796 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800797 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700798 type = i;
799 break;
800 }
801 }
802
803 if (type < 0) {
804 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700805 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700806
Mathias Agopian8b736f12012-08-13 17:54:26 -0700807 // TODO: Not sure if display density should handled by SF any longer
808 class Density {
809 static int getDensityFromProperty(char const* propName) {
810 char property[PROPERTY_VALUE_MAX];
811 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800812 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700813 density = atoi(property);
814 }
815 return density;
816 }
817 public:
818 static int getEmuDensity() {
819 return getDensityFromProperty("qemu.sf.lcd_density"); }
820 static int getBuildDensity() {
821 return getDensityFromProperty("ro.sf.lcd_density"); }
822 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700823
Dan Stoza7f7da322014-05-02 15:26:25 -0700824 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700825
Steven Thomas6d8110b2017-08-31 18:24:21 -0700826 ConditionalLock _l(mStateLock,
827 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800828 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700829 DisplayInfo info = DisplayInfo();
830
Dan Stoza9e56aa02015-11-02 13:00:03 -0800831 float xdpi = hwConfig->getDpiX();
832 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700833
834 if (type == DisplayDevice::DISPLAY_PRIMARY) {
835 // The density of the device is provided by a build property
836 float density = Density::getBuildDensity() / 160.0f;
837 if (density == 0) {
838 // the build doesn't provide a density -- this is wrong!
839 // use xdpi instead
840 ALOGE("ro.sf.lcd_density must be defined as a build property");
841 density = xdpi / 160.0f;
842 }
843 if (Density::getEmuDensity()) {
844 // if "qemu.sf.lcd_density" is specified, it overrides everything
845 xdpi = ydpi = density = Density::getEmuDensity();
846 density /= 160.0f;
847 }
848 info.density = density;
849
850 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700851 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800852 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700853 } else {
854 // TODO: where should this value come from?
855 static const int TV_DENSITY = 213;
856 info.density = TV_DENSITY / 160.0f;
857 info.orientation = 0;
858 }
859
Dan Stoza9e56aa02015-11-02 13:00:03 -0800860 info.w = hwConfig->getWidth();
861 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700862 info.xdpi = xdpi;
863 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800864 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900865 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800866
Andy McFadden91b2ca82014-06-13 14:04:23 -0700867 // This is how far in advance a buffer must be queued for
868 // presentation at a given time. If you want a buffer to appear
869 // on the screen at time N, you must submit the buffer before
870 // (N - presentationDeadline).
871 //
872 // Normally it's one full refresh period (to give SF a chance to
873 // latch the buffer), but this can be reduced by configuring a
874 // DispSync offset. Any additional delays introduced by the hardware
875 // composer or panel must be accounted for here.
876 //
877 // We add an additional 1ms to allow for processing time and
878 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800879 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800880 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700881
882 // All non-virtual displays are currently considered secure.
883 info.secure = true;
884
Michael Wright28f24d02016-07-12 13:30:53 -0700885 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700886 }
887
Dan Stoza7f7da322014-05-02 15:26:25 -0700888 return NO_ERROR;
889}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700890
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800891status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700892 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800893 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700894 return BAD_VALUE;
895 }
896
897 // FIXME for now we always return stats for the primary display
898 memset(stats, 0, sizeof(*stats));
899 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
900 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
901 return NO_ERROR;
902}
903
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700904int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800905 if (display == nullptr) {
906 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800907 return BAD_VALUE;
908 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700909
910 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800911 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700912 return device->getActiveConfig();
913 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700914
Dan Stoza24a42e92015-03-09 10:04:11 -0700915 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700916}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700917
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700918void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
919 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
920 this);
921 int32_t type = hw->getDisplayType();
922 int currentMode = hw->getActiveConfig();
923
924 if (mode == currentMode) {
925 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
926 return;
927 }
928
929 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
930 ALOGW("Trying to set config for virtual display");
931 return;
932 }
933
934 hw->setActiveConfig(mode);
935 getHwComposer().setActiveConfig(type, mode);
936}
937
938status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
939 class MessageSetActiveConfig: public MessageBase {
940 SurfaceFlinger& mFlinger;
941 sp<IBinder> mDisplay;
942 int mMode;
943 public:
944 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
945 int mode) :
946 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
947 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700948 Vector<DisplayInfo> configs;
949 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700950 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700951 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700952 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700953 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700954 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700955 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800956 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700957 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700958 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700959 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
960 ALOGW("Attempt to set active config = %d for virtual display",
961 mMode);
962 } else {
963 mFlinger.setActiveConfigInternal(hw, mMode);
964 }
965 return true;
966 }
967 };
968 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
969 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700970 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700971}
Michael Wright28f24d02016-07-12 13:30:53 -0700972status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -0700973 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700974 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
975 return BAD_VALUE;
976 }
977
978 if (!display.get()) {
979 return NAME_NOT_FOUND;
980 }
981
982 int32_t type = NAME_NOT_FOUND;
983 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
984 if (display == mBuiltinDisplays[i]) {
985 type = i;
986 break;
987 }
988 }
989
990 if (type < 0) {
991 return type;
992 }
993
Peiyong Lina52f0292018-03-14 17:26:31 -0700994 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700995 {
996 ConditionalLock _l(mStateLock,
997 std::this_thread::get_id() != mMainThreadId);
998 modes = getHwComposer().getColorModes(type);
999 }
Michael Wright28f24d02016-07-12 13:30:53 -07001000 outColorModes->clear();
1001 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1002
1003 return NO_ERROR;
1004}
1005
Peiyong Lina52f0292018-03-14 17:26:31 -07001006ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001007 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -07001008 if (device != nullptr) {
1009 return device->getActiveColorMode();
1010 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001011 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001012}
1013
1014void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001015 ColorMode mode, Dataspace dataSpace,
1016 RenderIntent renderIntent) {
Michael Wright28f24d02016-07-12 13:30:53 -07001017 int32_t type = hw->getDisplayType();
Peiyong Lina52f0292018-03-14 17:26:31 -07001018 ColorMode currentMode = hw->getActiveColorMode();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001019 Dataspace currentDataSpace = hw->getCompositionDataSpace();
Peiyong Lin38e9a562018-04-10 16:24:20 -07001020 RenderIntent currentRenderIntent = hw->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001021
Peiyong Lin38e9a562018-04-10 16:24:20 -07001022 if (mode == currentMode && dataSpace == currentDataSpace &&
1023 renderIntent == currentRenderIntent) {
1024 return;
1025 }
1026
1027 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1028 ALOGW("Trying to set config for virtual display");
1029 return;
1030 }
1031
1032 hw->setActiveColorMode(mode);
1033 hw->setCompositionDataSpace(dataSpace);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001034 hw->setActiveRenderIntent(renderIntent);
1035 getHwComposer().setActiveColorMode(type, mode, renderIntent);
1036
1037 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
1038 decodeColorMode(mode).c_str(), mode,
1039 decodeRenderIntent(renderIntent).c_str(), renderIntent,
1040 hw->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001041}
1042
1043
1044status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001045 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -07001046 class MessageSetActiveColorMode: public MessageBase {
1047 SurfaceFlinger& mFlinger;
1048 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -07001049 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001050 public:
1051 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -07001052 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -07001053 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1054 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -07001055 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001056 mFlinger.getDisplayColorModes(mDisplay, &modes);
1057 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -07001058 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001059 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1060 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001061 return true;
1062 }
1063 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1064 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001065 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1066 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001067 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001068 ALOGW("Attempt to set active color mode %s %d for virtual display",
1069 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001070 } else {
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001071 mFlinger.setActiveColorModeInternal(hw, mMode, Dataspace::UNKNOWN,
1072 RenderIntent::COLORIMETRIC);
Michael Wright28f24d02016-07-12 13:30:53 -07001073 }
1074 return true;
1075 }
1076 };
1077 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1078 postMessageSync(msg);
1079 return NO_ERROR;
1080}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001081
Svetoslavd85084b2014-03-20 10:28:31 -07001082status_t SurfaceFlinger::clearAnimationFrameStats() {
1083 Mutex::Autolock _l(mStateLock);
1084 mAnimFrameTracker.clearStats();
1085 return NO_ERROR;
1086}
1087
1088status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1089 Mutex::Autolock _l(mStateLock);
1090 mAnimFrameTracker.getStats(outStats);
1091 return NO_ERROR;
1092}
1093
Dan Stozac4f471e2016-03-24 09:31:08 -07001094status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1095 HdrCapabilities* outCapabilities) const {
1096 Mutex::Autolock _l(mStateLock);
1097
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001098 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001099 if (displayDevice == nullptr) {
1100 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1101 return BAD_VALUE;
1102 }
1103
Peiyong Linfb069302018-04-25 14:34:31 -07001104 // At this point the DisplayDeivce should already be set up,
1105 // meaning the luminance information is already queried from
1106 // hardware composer and stored properly.
1107 const HdrCapabilities& capabilities = displayDevice->getHdrCapabilities();
1108 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1109 capabilities.getDesiredMaxLuminance(),
1110 capabilities.getDesiredMaxAverageLuminance(),
1111 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001112
1113 return NO_ERROR;
1114}
1115
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001116status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001117 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1118 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001119
Chia-I Wu90f669f2017-10-05 14:24:41 -07001120 if (mInjectVSyncs == enable) {
1121 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001122 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001123
1124 if (enable) {
1125 ALOGV("VSync Injections enabled");
1126 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001127 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001128 mInjectorEventThread = std::make_unique<
1129 impl::EventThread>(mVSyncInjector.get(),
1130 [this]() { resyncWithRateLimit(); },
1131 impl::EventThread::InterceptVSyncsCallback(),
1132 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001133 }
Lloyd Pique9123ae52018-01-22 17:14:00 -08001134 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001135 } else {
1136 ALOGV("VSync Injections disabled");
Lloyd Pique9123ae52018-01-22 17:14:00 -08001137 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001138 }
1139
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001140 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001141 });
1142 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001143 return NO_ERROR;
1144}
1145
1146status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001147 Mutex::Autolock _l(mStateLock);
1148
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001149 if (!mInjectVSyncs) {
1150 ALOGE("VSync Injections not enabled");
1151 return BAD_VALUE;
1152 }
1153 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1154 ALOGV("Injecting VSync inside SurfaceFlinger");
1155 mVSyncInjector->onInjectSyncEvent(when);
1156 }
1157 return NO_ERROR;
1158}
1159
Lloyd Pique755e3192018-01-31 16:46:15 -08001160status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1161 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001162 IPCThreadState* ipc = IPCThreadState::self();
1163 const int pid = ipc->getCallingPid();
1164 const int uid = ipc->getCallingUid();
1165 if ((uid != AID_SHELL) &&
1166 !PermissionCache::checkPermission(sDump, pid, uid)) {
1167 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1168 return PERMISSION_DENIED;
1169 }
1170
1171 // Try to acquire a lock for 1s, fail gracefully
1172 const status_t err = mStateLock.timedLock(s2ns(1));
1173 const bool locked = (err == NO_ERROR);
1174 if (!locked) {
1175 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1176 return TIMED_OUT;
1177 }
1178
1179 outLayers->clear();
1180 mCurrentState.traverseInZOrder([&](Layer* layer) {
1181 outLayers->push_back(layer->getLayerDebugInfo());
1182 });
1183
1184 mStateLock.unlock();
1185 return NO_ERROR;
1186}
1187
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001188// ----------------------------------------------------------------------------
1189
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001190sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1191 ISurfaceComposer::VsyncSource vsyncSource) {
1192 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1193 return mSFEventThread->createEventConnection();
1194 } else {
1195 return mEventThread->createEventConnection();
1196 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001197}
1198
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001199// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001200
1201void SurfaceFlinger::waitForEvent() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001202 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001203}
1204
1205void SurfaceFlinger::signalTransaction() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001206 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001207}
1208
1209void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001210 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001211}
1212
1213void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001214 mRefreshPending = true;
Lloyd Pique9123ae52018-01-22 17:14:00 -08001215 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001216}
1217
1218status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001219 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001220 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001221}
1222
1223status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001224 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001225 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001226 if (res == NO_ERROR) {
1227 msg->wait();
1228 }
1229 return res;
1230}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001231
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001232void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001233 do {
1234 waitForEvent();
1235 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001236}
1237
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001238void SurfaceFlinger::enableHardwareVsync() {
1239 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001240 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001241 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001242 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1243 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001244 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001245 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001246}
1247
Jesse Hall948fe0c2013-10-14 12:56:09 -07001248void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001249 Mutex::Autolock _l(mHWVsyncLock);
1250
Jesse Hall948fe0c2013-10-14 12:56:09 -07001251 if (makeAvailable) {
1252 mHWVsyncAvailable = true;
1253 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001254 // Hardware vsync is not currently available, so abort the resync
1255 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001256 return;
1257 }
1258
David Sodman105b7dc2017-11-04 20:28:14 -07001259 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001260 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001261
1262 mPrimaryDispSync.reset();
1263 mPrimaryDispSync.setPeriod(period);
1264
1265 if (!mPrimaryHWVsyncEnabled) {
1266 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001267 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1268 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001269 mPrimaryHWVsyncEnabled = true;
1270 }
1271}
1272
Jesse Hall948fe0c2013-10-14 12:56:09 -07001273void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001274 Mutex::Autolock _l(mHWVsyncLock);
1275 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001276 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1277 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001278 mPrimaryDispSync.endResync();
1279 mPrimaryHWVsyncEnabled = false;
1280 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001281 if (makeUnavailable) {
1282 mHWVsyncAvailable = false;
1283 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001284}
1285
Tim Murray4a4e4a22016-04-19 16:29:23 +00001286void SurfaceFlinger::resyncWithRateLimit() {
1287 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001288
1289 // No explicit locking is needed here since EventThread holds a lock while calling this method
1290 static nsecs_t sLastResyncAttempted = 0;
1291 const nsecs_t now = systemTime();
1292 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001293 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001294 }
Dan Stoza57164302017-05-08 14:03:54 -07001295 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001296}
1297
Steven Thomasb02664d2017-07-26 18:48:28 -07001298void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1299 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001300 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001301 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001302 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001303 return;
1304 }
1305
1306 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001307 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001308 return;
1309 }
1310
Jamie Gennisd1700752013-10-14 12:22:52 -07001311 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001312
Jamie Gennisd1700752013-10-14 12:22:52 -07001313 { // Scope for the lock
1314 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001315 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001316 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001317 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001318 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001319
1320 if (needsHwVsync) {
1321 enableHardwareVsync();
1322 } else {
1323 disableHardwareVsync(false);
1324 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001325}
1326
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001327void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001328 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1329 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001330}
1331
Lloyd Pique715a2c12017-12-14 17:18:08 -08001332void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1333 HWC2::Connection connection) {
1334 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1335 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001336
Lloyd Piqueba04e622017-12-14 17:11:26 -08001337 // Ignore events that do not have the right sequenceId.
1338 if (sequenceId != getBE().mComposerSequenceId) {
1339 return;
1340 }
1341
Steven Thomasb02664d2017-07-26 18:48:28 -07001342 // Only lock if we're not on the main thread. This function is normally
1343 // called on a hwbinder thread, but for the primary display it's called on
1344 // the main thread with the state lock already held, so don't attempt to
1345 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001346 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001347
Lloyd Pique715a2c12017-12-14 17:18:08 -08001348 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001349
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001350 if (std::this_thread::get_id() == mMainThreadId) {
1351 // Process all pending hot plug events immediately if we are on the main thread.
1352 processDisplayHotplugEventsLocked();
1353 }
1354
Lloyd Piqueba04e622017-12-14 17:11:26 -08001355 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001356}
1357
Steven Thomasb02664d2017-07-26 18:48:28 -07001358void SurfaceFlinger::onRefreshReceived(int sequenceId,
1359 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001360 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001361 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001362 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001363 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001364 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001365}
1366
Dan Stoza9e56aa02015-11-02 13:00:03 -08001367void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001368 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001369 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001370 getHwComposer().setVsyncEnabled(disp,
1371 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001372}
1373
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001374// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001375void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001376 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001377 // Clear the drawing state so that the logic inside of
1378 // handleTransactionLocked will fire. It will determine the delta between
1379 // mCurrentState and mDrawingState and re-apply all changes when we make the
1380 // transition.
1381 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001382 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001383 mDisplays.clear();
1384}
1385
Steven Thomas050b2c82017-03-06 11:45:16 -08001386void SurfaceFlinger::updateVrFlinger() {
1387 if (!mVrFlinger)
1388 return;
1389 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001390 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001391 return;
1392 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001393
David Sodman105b7dc2017-11-04 20:28:14 -07001394 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001395 ALOGE("Vr flinger is only supported for remote hardware composer"
1396 " service connections. Ignoring request to transition to vr"
1397 " flinger.");
1398 mVrFlingerRequestsDisplay = false;
1399 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001400 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001401
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001402 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001403
Steven Thomasb02664d2017-07-26 18:48:28 -07001404 int currentDisplayPowerMode = getDisplayDeviceLocked(
1405 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001406
Steven Thomasb02664d2017-07-26 18:48:28 -07001407 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001408 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001409 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001410
Steven Thomasb02664d2017-07-26 18:48:28 -07001411 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001412 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001413 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1414 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001415 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001416
David Sodman105b7dc2017-11-04 20:28:14 -07001417 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1418 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001419
1420 if (vrFlingerRequestsDisplay) {
1421 mVrFlinger->GrantDisplayOwnership();
1422 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001423 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001424 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001425
1426 mVisibleRegionsDirty = true;
1427 invalidateHwcGeometry();
1428
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001429 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001430 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1431 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1432 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001433
Steven Thomasb02664d2017-07-26 18:48:28 -07001434 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001435 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001436 const nsecs_t period = activeConfig->getVsyncPeriod();
1437 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001438
Steven Thomasb02664d2017-07-26 18:48:28 -07001439 // Use phase of 0 since phase is not known.
1440 // Use latency of 0, which will snap to the ideal latency.
1441 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001442
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001443 android_atomic_or(1, &mRepaintEverything);
1444 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001445}
1446
Mathias Agopian4fec8732012-06-29 14:12:52 -07001447void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001448 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001449 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001450 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001451 bool frameMissed = !mHadClientComposition &&
1452 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001453 (mPreviousPresentFence->getSignalTime() ==
1454 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001455 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001456 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001457 mTimeStats.incrementMissedFrames();
1458 if (mPropagateBackpressure) {
1459 signalLayerUpdate();
1460 break;
1461 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001462 }
Dan Stoza50182882016-07-08 12:02:20 -07001463
Steven Thomas050b2c82017-03-06 11:45:16 -08001464 // Now that we're going to make it to the handleMessageTransaction()
1465 // call below it's safe to call updateVrFlinger(), which will
1466 // potentially trigger a display handoff.
1467 updateVrFlinger();
1468
Dan Stoza6b9454d2014-11-07 16:00:59 -08001469 bool refreshNeeded = handleMessageTransaction();
1470 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001471 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001472 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001473 // Signal a refresh if a transaction modified the window state,
1474 // a new buffer was latched, or if HWC has requested a full
1475 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001476 signalRefresh();
1477 }
1478 break;
1479 }
1480 case MessageQueue::REFRESH: {
1481 handleMessageRefresh();
1482 break;
1483 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001484 }
1485}
1486
Dan Stoza6b9454d2014-11-07 16:00:59 -08001487bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001488 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001489 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001490 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001491 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001492 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001493 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001494}
1495
Dan Stoza6b9454d2014-11-07 16:00:59 -08001496bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001497 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001498 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001499}
1500
1501void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001502 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001503
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001504 mRefreshPending = false;
1505
Pablo Ceballos40845df2016-01-25 17:41:15 -08001506 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001507
Brian Andersond6927fb2016-07-23 23:37:30 -07001508 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001509 rebuildLayerStacks();
1510 setUpHWComposer();
1511 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001512 doTracing("handleRefresh");
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001513 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001514 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001515 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001516
David Sodman105b7dc2017-11-04 20:28:14 -07001517 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001518
1519 mHadClientComposition = false;
1520 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1521 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1522 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001523 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001524 }
Dan Stoza2713c302018-03-28 17:07:36 -07001525 mVsyncModulator.setLastFrameUsedRenderEngine(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001526
Dan Stoza9e56aa02015-11-02 13:00:03 -08001527 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001528}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001529
Mathias Agopiancd60f992012-08-16 16:28:27 -07001530void SurfaceFlinger::doDebugFlashRegions()
1531{
1532 // is debugging enabled
1533 if (CC_LIKELY(!mDebugRegion))
1534 return;
1535
1536 const bool repaintEverything = mRepaintEverything;
1537 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1538 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001539 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001540 // transform the dirty region into this screen's coordinate space
1541 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1542 if (!dirtyRegion.isEmpty()) {
1543 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001544 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001545
1546 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001547 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001548 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001549 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1550
Mathias Agopianda27af92012-09-13 18:17:13 -07001551 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001552 }
1553 }
1554 }
1555
1556 postFramebuffer();
1557
1558 if (mDebugRegion > 1) {
1559 usleep(mDebugRegion * 1000);
1560 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001561
Dan Stoza9e56aa02015-11-02 13:00:03 -08001562 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001563 auto& displayDevice = mDisplays[displayId];
1564 if (!displayDevice->isDisplayOn()) {
1565 continue;
1566 }
1567
David Sodman105b7dc2017-11-04 20:28:14 -07001568 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1569 ALOGE_IF(result != NO_ERROR,
1570 "prepareFrame for display %zd failed:"
1571 " %d (%s)",
1572 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001573 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001574}
1575
Adrian Roos1e1a1282017-11-01 19:05:31 +01001576void SurfaceFlinger::doTracing(const char* where) {
1577 ATRACE_CALL();
1578 ATRACE_NAME(where);
1579 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001580 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001581 }
1582}
1583
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001584void SurfaceFlinger::logLayerStats() {
1585 ATRACE_CALL();
1586 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1587 int32_t hwcId = -1;
1588 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1589 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1590 if (displayDevice->isPrimary()) {
1591 hwcId = displayDevice->getHwcDisplayId();
1592 break;
1593 }
1594 }
1595 if (hwcId < 0) {
1596 ALOGE("LayerStats: Hmmm, no primary display?");
1597 return;
1598 }
1599 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1600 }
1601}
1602
Brian Andersond6927fb2016-07-23 23:37:30 -07001603void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001604{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001605 ATRACE_CALL();
1606 ALOGV("preComposition");
1607
Mathias Agopiancd60f992012-08-16 16:28:27 -07001608 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001609 mDrawingState.traverseInZOrder([&](Layer* layer) {
1610 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001611 needExtraInvalidate = true;
1612 }
Robert Carr2047fae2016-11-28 14:09:09 -08001613 });
1614
Mathias Agopiancd60f992012-08-16 16:28:27 -07001615 if (needExtraInvalidate) {
1616 signalLayerUpdate();
1617 }
1618}
1619
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001620void SurfaceFlinger::updateCompositorTiming(
1621 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1622 std::shared_ptr<FenceTime>& presentFenceTime) {
1623 // Update queue of past composite+present times and determine the
1624 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001625 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001626 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001627 while (!getBE().mCompositePresentTimes.empty()) {
1628 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001629 // Cached values should have been updated before calling this method,
1630 // which helps avoid duplicate syscalls.
1631 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1632 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1633 break;
1634 }
1635 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001636 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001637 }
1638
1639 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001640 while (getBE().mCompositePresentTimes.size() > 16) {
1641 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001642 }
1643
Brian Andersond0010582017-03-07 13:20:31 -08001644 setCompositorTimingSnapped(
1645 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1646}
1647
1648void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1649 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001650 // Integer division and modulo round toward 0 not -inf, so we need to
1651 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001652 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001653 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1654 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1655
Brian Andersond0010582017-03-07 13:20:31 -08001656 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1657 if (idealLatency <= 0) {
1658 idealLatency = vsyncInterval;
1659 }
1660
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001661 // Snap the latency to a value that removes scheduling jitter from the
1662 // composition and present times, which often have >1ms of jitter.
1663 // Reducing jitter is important if an app attempts to extrapolate
1664 // something (such as user input) to an accurate diasplay time.
1665 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1666 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001667 nsecs_t bias = vsyncInterval / 2;
1668 int64_t extraVsyncs =
1669 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1670 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1671 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001672
David Sodman99974d22017-11-28 12:04:33 -08001673 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1674 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1675 getBE().mCompositorTiming.interval = vsyncInterval;
1676 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001677}
1678
1679void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001680{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001681 ATRACE_CALL();
1682 ALOGV("postComposition");
1683
Brian Anderson3546a3f2016-07-14 11:51:14 -07001684 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001685 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001686 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001687 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001688 }
1689
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001690 // |mStateLock| not needed as we are on the main thread
1691 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001692
David Sodman73beded2017-11-15 11:56:06 -08001693 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001694 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001695 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001696 glCompositionDoneFenceTime =
1697 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001698 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001699 } else {
1700 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1701 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001702
David Sodman73beded2017-11-15 11:56:06 -08001703 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001704 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001705 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001706 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001707
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001708 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1709 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1710
1711 // We use the refreshStartTime which might be sampled a little later than
1712 // when we started doing work for this frame, but that should be okay
1713 // since updateCompositorTiming has snapping logic.
1714 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001715 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001716 CompositorTiming compositorTiming;
1717 {
David Sodman99974d22017-11-28 12:04:33 -08001718 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1719 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001720 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001721
Robert Carr2047fae2016-11-28 14:09:09 -08001722 mDrawingState.traverseInZOrder([&](Layer* layer) {
1723 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001724 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001725 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001726 recordBufferingStats(layer->getName().string(),
1727 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001728 }
Robert Carr2047fae2016-11-28 14:09:09 -08001729 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001730
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001731 if (presentFenceTime->isValid()) {
1732 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001733 enableHardwareVsync();
1734 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001735 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001736 }
1737 }
1738
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001739 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001740 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001741 enableHardwareVsync();
1742 }
1743 }
1744
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001745 if (mAnimCompositionPending) {
1746 mAnimCompositionPending = false;
1747
Brian Anderson4e606e32017-03-16 15:34:57 -07001748 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001749 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001750 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001751 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001752 // The HWC doesn't support present fences, so use the refresh
1753 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001754 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001755 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001756 mAnimFrameTracker.setActualPresentTime(presentTime);
1757 }
1758 mAnimFrameTracker.advanceFrame();
1759 }
Dan Stozab90cf072015-03-05 11:05:59 -08001760
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001761 mTimeStats.incrementTotalFrames();
1762 if (mHadClientComposition) {
1763 mTimeStats.incrementClientCompositionFrames();
1764 }
1765
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001766 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1767 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001768 return;
1769 }
1770
1771 nsecs_t currentTime = systemTime();
1772 if (mHasPoweredOff) {
1773 mHasPoweredOff = false;
1774 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001775 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001776 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001777 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1778 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001779 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001780 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001781 }
David Sodman4a36e932017-11-07 14:29:47 -08001782 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001783 }
David Sodman4a36e932017-11-07 14:29:47 -08001784 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001785}
1786
1787void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001788 ATRACE_CALL();
1789 ALOGV("rebuildLayerStacks");
1790
Mathias Agopiancd60f992012-08-16 16:28:27 -07001791 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001792 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001793 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001794 mVisibleRegionsDirty = false;
1795 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001796
Jeff Sharkey76488112017-02-27 14:15:18 -07001797 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1798 Region opaqueRegion;
1799 Region dirtyRegion;
1800 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001801 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001802 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1803 const Transform& tr(displayDevice->getTransform());
1804 const Rect bounds(displayDevice->getBounds());
1805 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001806 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001807
Jeff Sharkey76488112017-02-27 14:15:18 -07001808 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001809 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001810 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1811 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001812 Region drawRegion(tr.transform(
1813 layer->visibleNonTransparentRegion));
1814 drawRegion.andSelf(bounds);
1815 if (!drawRegion.isEmpty()) {
1816 layersSortedByZ.add(layer);
1817 } else {
1818 // Clear out the HWC layer if this layer was
1819 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001820 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001821 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001822 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001823 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001824 // WM changes displayDevice->layerStack upon sleep/awake.
1825 // Here we make sure we delete the HWC layers even if
1826 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001827 hwcLayerDestroyed = layer->destroyHwcLayer(
1828 displayDevice->getHwcDisplayId());
1829 }
1830
1831 // If a layer is not going to get a release fence because
1832 // it is invisible, but it is also going to release its
1833 // old buffer, add it to the list of layers needing
1834 // fences.
1835 if (hwcLayerDestroyed) {
1836 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1837 mLayersWithQueuedFrames.cend(), layer);
1838 if (found != mLayersWithQueuedFrames.cend()) {
1839 layersNeedingFences.add(layer);
1840 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001841 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001842 });
1843 }
1844 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001845 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001846 displayDevice->undefinedRegion.set(bounds);
1847 displayDevice->undefinedRegion.subtractSelf(
1848 tr.transform(opaqueRegion));
1849 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001850 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001851 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001852}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001853
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001854// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001855// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001856// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001857// - Dataspace::DISPLAY_P3
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001858// The returned HDR data space is one of
1859// - Dataspace::UNKNOWN
1860// - Dataspace::BT2020_HLG
1861// - Dataspace::BT2020_PQ
1862Dataspace SurfaceFlinger::getBestDataspace(
1863 const sp<const DisplayDevice>& displayDevice, Dataspace* outHdrDataSpace) const {
1864 Dataspace bestDataSpace = Dataspace::SRGB;
1865 *outHdrDataSpace = Dataspace::UNKNOWN;
1866
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001867 for (const auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu1b6bafc2018-05-22 12:03:00 -07001868 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001869 case Dataspace::V0_SCRGB:
1870 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001871 case Dataspace::DISPLAY_P3:
Chia-I Wu0607fbe2018-05-18 10:59:36 -07001872 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001873 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001874 case Dataspace::BT2020_PQ:
1875 case Dataspace::BT2020_ITU_PQ:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001876 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001877 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001878 case Dataspace::BT2020_HLG:
1879 case Dataspace::BT2020_ITU_HLG:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001880 // When there's mixed PQ content and HLG content, we set the HDR
1881 // data space to be BT2020_PQ and convert HLG to PQ.
1882 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1883 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001884 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001885 break;
1886 default:
1887 break;
1888 }
Romain Guy54f154a2017-10-24 21:40:32 +01001889 }
1890
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001891 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001892}
1893
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001894// Pick the ColorMode / Dataspace for the display device.
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001895void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& displayDevice,
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001896 ColorMode* outMode, Dataspace* outDataSpace,
1897 RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001898 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1899 *outMode = ColorMode::NATIVE;
1900 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001901 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001902 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001903 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001904
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001905 Dataspace hdrDataSpace;
1906 Dataspace bestDataSpace = getBestDataspace(displayDevice, &hdrDataSpace);
1907
Chia-I Wu0d711262018-05-21 15:19:35 -07001908 RenderIntent intent;
1909 switch (mDisplayColorSetting) {
1910 case DisplayColorSetting::MANAGED:
1911 case DisplayColorSetting::UNMANAGED:
1912 intent = RenderIntent::COLORIMETRIC;
1913 break;
1914 case DisplayColorSetting::ENHANCED:
1915 intent = RenderIntent::ENHANCE;
1916 break;
1917 default: // vendor display color setting
1918 intent = static_cast<RenderIntent>(mDisplayColorSetting);
1919 break;
1920 }
Chia-I Wu0607fbe2018-05-18 10:59:36 -07001921
1922 // respect hdrDataSpace only when there is modern HDR support
1923 if (hdrDataSpace != Dataspace::UNKNOWN && displayDevice->hasModernHdrSupport(hdrDataSpace)) {
1924 bestDataSpace = hdrDataSpace;
1925 intent = mDisplayColorSetting == DisplayColorSetting::ENHANCED ?
1926 RenderIntent::TONE_MAP_ENHANCE : RenderIntent::TONE_MAP_COLORIMETRIC;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001927 }
1928
Chia-I Wu0607fbe2018-05-18 10:59:36 -07001929 displayDevice->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001930}
1931
Mathias Agopiancd60f992012-08-16 16:28:27 -07001932void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001933 ATRACE_CALL();
1934 ALOGV("setUpHWComposer");
1935
Jesse Hall028dc8f2013-08-20 16:35:32 -07001936 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Dan Stozac7a25ad2018-04-12 11:45:09 -07001937 bool dirty = !mDisplays[dpy]->getDirtyRegion(mRepaintEverything).isEmpty();
Jesse Hallb7a05492014-08-14 15:45:06 -07001938 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1939 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1940
1941 // If nothing has changed (!dirty), don't recompose.
1942 // If something changed, but we don't currently have any visible layers,
1943 // and didn't when we last did a composition, then skip it this time.
1944 // The second rule does two things:
1945 // - When all layers are removed from a display, we'll emit one black
1946 // frame, then nothing more until we get new layers.
1947 // - When a display is created with a private layer stack, we won't
1948 // emit any black frames until a layer is added to the layer stack.
1949 bool mustRecompose = dirty && !(empty && wasEmpty);
1950
1951 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1952 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1953 mustRecompose ? "doing" : "skipping",
1954 dirty ? "+" : "-",
1955 empty ? "+" : "-",
1956 wasEmpty ? "+" : "-");
1957
Dan Stoza71433162014-02-04 16:22:36 -08001958 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001959
1960 if (mustRecompose) {
1961 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1962 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001963 }
1964
Dan Stoza9e56aa02015-11-02 13:00:03 -08001965 // build the h/w work list
1966 if (CC_UNLIKELY(mGeometryInvalid)) {
1967 mGeometryInvalid = false;
1968 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1969 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1970 const auto hwcId = displayDevice->getHwcDisplayId();
1971 if (hwcId >= 0) {
1972 const Vector<sp<Layer>>& currentLayers(
1973 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001974 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001975 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001976 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07001977 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001978 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001979 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001980 }
1981 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001982
Robert Carrae060832016-11-28 10:51:00 -08001983 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001984 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001985 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001986 }
1987 }
1988 }
1989 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001990 }
Riley Andrews03414a12014-07-01 14:22:59 -07001991
Dan Stoza9e56aa02015-11-02 13:00:03 -08001992 // Set the per-frame data
1993 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1994 auto& displayDevice = mDisplays[displayId];
1995 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001996
Dan Stoza9e56aa02015-11-02 13:00:03 -08001997 if (hwcId < 0) {
1998 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001999 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07002000 if (mDrawingState.colorMatrixChanged) {
2001 displayDevice->setColorTransform(mDrawingState.colorMatrix);
2002 status_t result = getBE().mHwc->setColorTransform(hwcId, mDrawingState.colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002003 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
2004 "display %zd: %d", displayId, result);
2005 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002006 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu1b6bafc2018-05-22 12:03:00 -07002007 if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2008 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Peiyong Lin62665892018-04-16 11:07:44 -07002009 !displayDevice->hasHDR10Support()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002010 layer->forceClientComposition(hwcId);
2011 }
Chia-I Wu1b6bafc2018-05-22 12:03:00 -07002012 if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
2013 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Peiyong Linf59a7192018-04-25 11:19:31 -07002014 !displayDevice->hasHLGSupport()) {
2015 layer->forceClientComposition(hwcId);
2016 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002017
chaviwc9232ed2017-11-14 15:31:15 -08002018 if (layer->getForceClientComposition(hwcId)) {
2019 ALOGV("[%s] Requesting Client composition", layer->getName().string());
2020 layer->setCompositionType(hwcId, HWC2::Composition::Client);
2021 continue;
2022 }
2023
Dan Stoza9e56aa02015-11-02 13:00:03 -08002024 layer->setPerFrameData(displayDevice);
2025 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002026
2027 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002028 ColorMode colorMode;
2029 Dataspace dataSpace;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002030 RenderIntent renderIntent;
2031 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
2032 setActiveColorModeInternal(displayDevice, colorMode, dataSpace, renderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002033 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002034 }
2035
Chia-I Wu28f320b2018-05-03 11:02:56 -07002036 mDrawingState.colorMatrixChanged = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002037
Dan Stoza9e56aa02015-11-02 13:00:03 -08002038 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002039 auto& displayDevice = mDisplays[displayId];
2040 if (!displayDevice->isDisplayOn()) {
2041 continue;
2042 }
2043
David Sodman105b7dc2017-11-04 20:28:14 -07002044 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002045 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2046 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002047 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002048}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002049
Mathias Agopiancd60f992012-08-16 16:28:27 -07002050void SurfaceFlinger::doComposition() {
2051 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002052 ALOGV("doComposition");
2053
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002054 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002055 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002056 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002057 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002058 // transform the dirty region into this screen's coordinate space
2059 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002060
2061 // repaint the framebuffer (if needed)
2062 doDisplayComposition(hw, dirtyRegion);
2063
Mathias Agopiancd60f992012-08-16 16:28:27 -07002064 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002065 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002066 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002067 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002068 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002069}
2070
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002071void SurfaceFlinger::postFramebuffer()
2072{
Mathias Agopian841cde52012-03-01 15:44:37 -08002073 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002074 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002075
Mathias Agopiana44b0412011-10-16 18:46:35 -07002076 const nsecs_t now = systemTime();
2077 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002078
Dan Stoza9e56aa02015-11-02 13:00:03 -08002079 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2080 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002081 if (!displayDevice->isDisplayOn()) {
2082 continue;
2083 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002084 const auto hwcId = displayDevice->getHwcDisplayId();
2085 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002086 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002087 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002088 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002089 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002090 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002091 // The layer buffer from the previous frame (if any) is released
2092 // by HWC only when the release fence from this frame (if any) is
2093 // signaled. Always get the release fence from HWC first.
2094 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002095 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002096
2097 // If the layer was client composited in the previous frame, we
2098 // need to merge with the previous client target acquire fence.
2099 // Since we do not track that, always merge with the current
2100 // client target acquire fence when it is available, even though
2101 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002102 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002103 releaseFence = Fence::merge("LayerRelease", releaseFence,
2104 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002105 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002106
Dan Stoza9e56aa02015-11-02 13:00:03 -08002107 layer->onLayerDisplayed(releaseFence);
2108 }
Chia-I Wu83806892017-11-16 10:50:20 -08002109
2110 // We've got a list of layers needing fences, that are disjoint with
2111 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2112 // supply them with the present fence.
2113 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002114 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002115 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2116 layer->onLayerDisplayed(presentFence);
2117 }
2118 }
2119
Dan Stoza9e56aa02015-11-02 13:00:03 -08002120 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002121 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002122 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002123 }
2124
Mathias Agopiana44b0412011-10-16 18:46:35 -07002125 mLastSwapBufferTime = systemTime() - now;
2126 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002127
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002128 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002129 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2130 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2131 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2132 logFrameStats();
2133 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002134 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002135}
2136
Mathias Agopian87baae12012-07-31 12:38:26 -07002137void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002138{
Mathias Agopian841cde52012-03-01 15:44:37 -08002139 ATRACE_CALL();
2140
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002141 // here we keep a copy of the drawing state (that is the state that's
2142 // going to be overwritten by handleTransactionLocked()) outside of
2143 // mStateLock so that the side-effects of the State assignment
2144 // don't happen with mStateLock held (which can cause deadlocks).
2145 State drawingState(mDrawingState);
2146
Mathias Agopianca4d3602011-05-19 15:38:14 -07002147 Mutex::Autolock _l(mStateLock);
2148 const nsecs_t now = systemTime();
2149 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002150
Mathias Agopianca4d3602011-05-19 15:38:14 -07002151 // Here we're guaranteed that some transaction flags are set
2152 // so we can call handleTransactionLocked() unconditionally.
2153 // We call getTransactionFlags(), which will also clear the flags,
2154 // with mStateLock held to guarantee that mCurrentState won't change
2155 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002156
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002157 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002158 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002159 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002160
Mathias Agopianca4d3602011-05-19 15:38:14 -07002161 mLastTransactionTime = systemTime() - now;
2162 mDebugInTransaction = 0;
2163 invalidateHwcGeometry();
2164 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002165}
2166
Lloyd Pique715a2c12017-12-14 17:18:08 -08002167DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique09594832018-01-22 17:48:03 -08002168 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002169 // Figure out whether the event is for the primary display or an
2170 // external display by matching the Hwc display id against one for a
2171 // connected display. If we did not find a match, we then check what
2172 // displays are not already connected to determine the type. If we don't
2173 // have a connected primary display, we assume the new display is meant to
2174 // be the primary display, and then if we don't have an external display,
2175 // we assume it is that.
2176 const auto primaryDisplayId =
2177 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2178 const auto externalDisplayId =
2179 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2180 if (primaryDisplayId && primaryDisplayId == display) {
2181 return DisplayDevice::DISPLAY_PRIMARY;
2182 } else if (externalDisplayId && externalDisplayId == display) {
2183 return DisplayDevice::DISPLAY_EXTERNAL;
2184 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2185 return DisplayDevice::DISPLAY_PRIMARY;
2186 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2187 return DisplayDevice::DISPLAY_EXTERNAL;
2188 }
2189
2190 return DisplayDevice::DISPLAY_ID_INVALID;
2191}
2192
Lloyd Piqueba04e622017-12-14 17:11:26 -08002193void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2194 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002195 auto displayType = determineDisplayType(event.display, event.connection);
2196 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2197 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2198 continue;
2199 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002200
2201 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2202 ALOGE("External displays are not supported by the vr hardware composer.");
2203 continue;
2204 }
2205
Lloyd Pique715a2c12017-12-14 17:18:08 -08002206 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002207
2208 if (event.connection == HWC2::Connection::Connected) {
Steven Thomas3bed0522018-03-20 15:40:48 -07002209 if (!mBuiltinDisplays[displayType].get()) {
2210 ALOGV("Creating built in display %d", displayType);
2211 mBuiltinDisplays[displayType] = new BBinder();
2212 // All non-virtual displays are currently considered secure.
2213 DisplayDeviceState info(displayType, true);
2214 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2215 "Built-in Screen" : "External Screen";
2216 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
Lloyd Pique4d234852018-01-22 17:21:36 -08002217 mInterceptor->saveDisplayCreation(info);
Steven Thomas3bed0522018-03-20 15:40:48 -07002218 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002219 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002220 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002221
Lloyd Piquefcd86612017-12-14 17:15:36 -08002222 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2223 if (idx >= 0) {
2224 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Lloyd Pique4d234852018-01-22 17:21:36 -08002225 mInterceptor->saveDisplayDeletion(info.displayId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002226 mCurrentState.displays.removeItemsAt(idx);
2227 }
2228 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002229 }
2230
2231 processDisplayChangesLocked();
2232 }
2233
2234 mPendingHotplugEvents.clear();
2235}
2236
Lloyd Pique09594832018-01-22 17:48:03 -08002237sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2238 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2239 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002240 bool hasWideColorGamut = false;
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002241 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002242
Lloyd Pique09594832018-01-22 17:48:03 -08002243 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002244 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Lloyd Pique09594832018-01-22 17:48:03 -08002245 for (ColorMode colorMode : modes) {
2246 switch (colorMode) {
2247 case ColorMode::DISPLAY_P3:
2248 case ColorMode::ADOBE_RGB:
2249 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002250 hasWideColorGamut = true;
Lloyd Pique09594832018-01-22 17:48:03 -08002251 break;
2252 default:
2253 break;
2254 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002255
2256 std::vector<RenderIntent> renderIntents = getHwComposer().getRenderIntents(hwcId,
2257 colorMode);
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002258 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique09594832018-01-22 17:48:03 -08002259 }
2260 }
2261
Peiyong Lin62665892018-04-16 11:07:44 -07002262 HdrCapabilities hdrCapabilities;
2263 getHwComposer().getHdrCapabilities(hwcId, &hdrCapabilities);
Lloyd Pique09594832018-01-22 17:48:03 -08002264
2265 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2266 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2267
2268 /*
2269 * Create our display's surface
2270 */
2271 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2272 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
2273 renderSurface->setAsync(state.type >= DisplayDevice::DISPLAY_VIRTUAL);
2274 renderSurface->setNativeWindow(nativeWindow.get());
2275 const int displayWidth = renderSurface->queryWidth();
2276 const int displayHeight = renderSurface->queryHeight();
2277
2278 // Make sure that composition can never be stalled by a virtual display
2279 // consumer that isn't processing buffers fast enough. We have to do this
2280 // in two places:
2281 // * Here, in case the display is composed entirely by HWC.
2282 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2283 // window's swap interval in eglMakeCurrent, so they'll override the
2284 // interval we set here.
2285 if (state.type >= DisplayDevice::DISPLAY_VIRTUAL) {
2286 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2287 }
2288
2289 // virtual displays are always considered enabled
2290 auto initialPowerMode = (state.type >= DisplayDevice::DISPLAY_VIRTUAL) ? HWC_POWER_MODE_NORMAL
2291 : HWC_POWER_MODE_OFF;
2292
2293 sp<DisplayDevice> hw =
2294 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2295 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
Peiyong Lin2c327ac2018-04-19 22:06:34 -07002296 hasWideColorGamut, hdrCapabilities,
2297 getHwComposer().getSupportedPerFrameMetadata(hwcId),
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002298 hwcColorModes, initialPowerMode);
Lloyd Pique09594832018-01-22 17:48:03 -08002299
2300 if (maxFrameBufferAcquiredBuffers >= 3) {
2301 nativeWindowSurface->preallocateBuffers();
2302 }
2303
2304 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002305 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2306 if (hasWideColorGamut) {
Lloyd Pique09594832018-01-22 17:48:03 -08002307 defaultColorMode = ColorMode::SRGB;
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002308 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique09594832018-01-22 17:48:03 -08002309 }
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002310 setActiveColorModeInternal(hw, defaultColorMode, defaultDataSpace,
2311 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002312 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
2313 hw->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
2314 }
Lloyd Pique09594832018-01-22 17:48:03 -08002315 hw->setLayerStack(state.layerStack);
2316 hw->setProjection(state.orientation, state.viewport, state.frame);
2317 hw->setDisplayName(state.displayName);
2318
2319 return hw;
2320}
2321
Lloyd Pique347200f2017-12-14 17:00:15 -08002322void SurfaceFlinger::processDisplayChangesLocked() {
2323 // here we take advantage of Vector's copy-on-write semantics to
2324 // improve performance by skipping the transaction entirely when
2325 // know that the lists are identical
2326 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2327 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2328 if (!curr.isIdenticalTo(draw)) {
2329 mVisibleRegionsDirty = true;
2330 const size_t cc = curr.size();
2331 size_t dc = draw.size();
2332
2333 // find the displays that were removed
2334 // (ie: in drawing state but not in current state)
2335 // also handle displays that changed
2336 // (ie: displays that are in both lists)
2337 for (size_t i = 0; i < dc;) {
2338 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2339 if (j < 0) {
2340 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002341 // Call makeCurrent() on the primary display so we can
2342 // be sure that nothing associated with this display
2343 // is current.
2344 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2345 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2346 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2347 if (hw != nullptr) hw->disconnect(getHwComposer());
2348 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2349 mEventThread->onHotplugReceived(draw[i].type, false);
2350 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002351 } else {
2352 // this display is in both lists. see if something changed.
2353 const DisplayDeviceState& state(curr[j]);
2354 const wp<IBinder>& display(curr.keyAt(j));
2355 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2356 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2357 if (state_binder != draw_binder) {
2358 // changing the surface is like destroying and
2359 // recreating the DisplayDevice, so we just remove it
2360 // from the drawing state, so that it get re-added
2361 // below.
2362 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2363 if (hw != nullptr) hw->disconnect(getHwComposer());
2364 mDisplays.removeItem(display);
2365 mDrawingState.displays.removeItemsAt(i);
2366 dc--;
2367 // at this point we must loop to the next item
2368 continue;
2369 }
2370
2371 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2372 if (disp != nullptr) {
2373 if (state.layerStack != draw[i].layerStack) {
2374 disp->setLayerStack(state.layerStack);
2375 }
2376 if ((state.orientation != draw[i].orientation) ||
2377 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2378 disp->setProjection(state.orientation, state.viewport, state.frame);
2379 }
2380 if (state.width != draw[i].width || state.height != draw[i].height) {
2381 disp->setDisplaySize(state.width, state.height);
2382 }
2383 }
2384 }
2385 ++i;
2386 }
2387
2388 // find displays that were added
2389 // (ie: in current state but not in drawing state)
2390 for (size_t i = 0; i < cc; i++) {
2391 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2392 const DisplayDeviceState& state(curr[i]);
2393
2394 sp<DisplaySurface> dispSurface;
2395 sp<IGraphicBufferProducer> producer;
2396 sp<IGraphicBufferProducer> bqProducer;
2397 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002398 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002399
2400 int32_t hwcId = -1;
2401 if (state.isVirtualDisplay()) {
2402 // Virtual displays without a surface are dormant:
2403 // they have external state (layer stack, projection,
2404 // etc.) but no internal state (i.e. a DisplayDevice).
2405 if (state.surface != nullptr) {
2406 // Allow VR composer to use virtual displays.
2407 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2408 int width = 0;
2409 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2410 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2411 int height = 0;
2412 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2413 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2414 int intFormat = 0;
2415 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2416 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002417 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002418
2419 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2420 }
2421
2422 // TODO: Plumb requested format back up to consumer
2423
2424 sp<VirtualDisplaySurface> vds =
2425 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2426 bqProducer, bqConsumer,
2427 state.displayName);
2428
2429 dispSurface = vds;
2430 producer = vds;
2431 }
2432 } else {
2433 ALOGE_IF(state.surface != nullptr,
2434 "adding a supported display, but rendering "
2435 "surface is provided (%p), ignoring it",
2436 state.surface.get());
2437
2438 hwcId = state.type;
2439 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2440 producer = bqProducer;
2441 }
2442
2443 const wp<IBinder>& display(curr.keyAt(i));
2444 if (dispSurface != nullptr) {
Lloyd Pique09594832018-01-22 17:48:03 -08002445 mDisplays.add(display,
2446 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2447 producer));
Lloyd Pique347200f2017-12-14 17:00:15 -08002448 if (!state.isVirtualDisplay()) {
2449 mEventThread->onHotplugReceived(state.type, true);
2450 }
2451 }
2452 }
2453 }
2454 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002455
2456 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002457}
2458
Mathias Agopian87baae12012-07-31 12:38:26 -07002459void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002460{
Dan Stoza7dde5992015-05-22 09:51:44 -07002461 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002462 mCurrentState.traverseInZOrder([](Layer* layer) {
2463 layer->notifyAvailableFrames();
2464 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002465
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002466 /*
2467 * Traversal of the children
2468 * (perform the transaction for each of them if needed)
2469 */
2470
Mathias Agopian3559b072012-08-15 13:46:03 -07002471 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002472 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002473 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002474 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002475
2476 const uint32_t flags = layer->doTransaction(0);
2477 if (flags & Layer::eVisibleRegion)
2478 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002479 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002480 }
2481
2482 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002483 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002484 */
2485
Mathias Agopiane57f2922012-08-09 16:29:12 -07002486 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002487 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002488 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002489 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002490
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002491 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002492 // The transform hint might have changed for some layers
2493 // (either because a display has changed, or because a layer
2494 // as changed).
2495 //
2496 // Walk through all the layers in currentLayers,
2497 // and update their transform hint.
2498 //
2499 // If a layer is visible only on a single display, then that
2500 // display is used to calculate the hint, otherwise we use the
2501 // default display.
2502 //
2503 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2504 // the hint is set before we acquire a buffer from the surface texture.
2505 //
2506 // NOTE: layer transactions have taken place already, so we use their
2507 // drawing state. However, SurfaceFlinger's own transaction has not
2508 // happened yet, so we must use the current state layer list
2509 // (soon to become the drawing state list).
2510 //
2511 sp<const DisplayDevice> disp;
2512 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002513 bool first = true;
2514 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002515 // NOTE: we rely on the fact that layers are sorted by
2516 // layerStack first (so we don't have to traverse the list
2517 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002518 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002519 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002520 currentlayerStack = layerStack;
2521 // figure out if this layerstack is mirrored
2522 // (more than one display) if so, pick the default display,
2523 // if not, pick the only display it's on.
2524 disp.clear();
2525 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2526 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002527 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002528 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002529 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002530 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002531 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002532 break;
2533 }
2534 }
2535 }
2536 }
Chet Haase91d25932013-04-11 15:24:55 -07002537
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002538 if (disp == nullptr) {
2539 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2540 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002541
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002542 // could be null when this layer is using a layerStack
2543 // that is not visible on any display. Also can occur at
2544 // screen off/on times.
2545 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002546 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002547
2548 // disp can be null if there is no display available at all to get
2549 // the transform hint from.
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002550 if (disp != nullptr) {
2551 layer->updateTransformHint(disp);
2552 }
Robert Carr2047fae2016-11-28 14:09:09 -08002553
2554 first = false;
2555 });
Mathias Agopian84300952012-11-21 16:02:13 -08002556 }
2557
2558
Mathias Agopian3559b072012-08-15 13:46:03 -07002559 /*
2560 * Perform our own transaction if needed
2561 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002562
2563 if (mLayersAdded) {
2564 mLayersAdded = false;
2565 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002566 mVisibleRegionsDirty = true;
2567 }
2568
2569 // some layers might have been removed, so
2570 // we need to update the regions they're exposing.
2571 if (mLayersRemoved) {
2572 mLayersRemoved = false;
2573 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002574 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002575 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002576 // this layer is not visible anymore
2577 // TODO: we could traverse the tree from front to back and
2578 // compute the actual visible region
2579 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002580 Region visibleReg;
2581 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002582 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002583 }
Robert Carr2047fae2016-11-28 14:09:09 -08002584 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002585 }
2586
2587 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002588
2589 updateCursorAsync();
2590}
2591
2592void SurfaceFlinger::updateCursorAsync()
2593{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002594 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2595 auto& displayDevice = mDisplays[displayId];
2596 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002597 continue;
2598 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002599
2600 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2601 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002602 }
2603 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002604}
2605
2606void SurfaceFlinger::commitTransaction()
2607{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002608 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002609 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002610 for (const auto& l : mLayersPendingRemoval) {
2611 recordBufferingStats(l->getName().string(),
2612 l->getOccupancyHistory(true));
2613 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002614 }
2615 mLayersPendingRemoval.clear();
2616 }
2617
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002618 // If this transaction is part of a window animation then the next frame
2619 // we composite should be considered an animation as well.
2620 mAnimCompositionPending = mAnimTransactionPending;
2621
Mathias Agopian4fec8732012-06-29 14:12:52 -07002622 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002623 // clear the "changed" flags in current state
2624 mCurrentState.colorMatrixChanged = false;
2625
Robert Carr1f0a16a2016-10-24 16:27:39 -07002626 mDrawingState.traverseInZOrder([](Layer* layer) {
2627 layer->commitChildList();
2628 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002629 mTransactionPending = false;
2630 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002631 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002632}
2633
Chia-I Wuab0c3192017-08-01 11:29:00 -07002634void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002635 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002636{
Mathias Agopian841cde52012-03-01 15:44:37 -08002637 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002638 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002639
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002640 Region aboveOpaqueLayers;
2641 Region aboveCoveredLayers;
2642 Region dirty;
2643
Mathias Agopian87baae12012-07-31 12:38:26 -07002644 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002645
Robert Carr2047fae2016-11-28 14:09:09 -08002646 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002647 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002648 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002649
Jesse Hall01e29052013-02-19 16:13:35 -08002650 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002651 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002652 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002653
Mathias Agopianab028732010-03-16 16:41:46 -07002654 /*
2655 * opaqueRegion: area of a surface that is fully opaque.
2656 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002657 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002658
2659 /*
2660 * visibleRegion: area of a surface that is visible on screen
2661 * and not fully transparent. This is essentially the layer's
2662 * footprint minus the opaque regions above it.
2663 * Areas covered by a translucent surface are considered visible.
2664 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002665 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002666
2667 /*
2668 * coveredRegion: area of a surface that is covered by all
2669 * visible regions above it (which includes the translucent areas).
2670 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002671 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002672
Jesse Halla8026d22012-09-25 13:25:04 -07002673 /*
2674 * transparentRegion: area of a surface that is hinted to be completely
2675 * transparent. This is only used to tell when the layer has no visible
2676 * non-transparent regions and can be removed from the layer list. It
2677 * does not affect the visibleRegion of this layer or any layers
2678 * beneath it. The hint may not be correct if apps don't respect the
2679 * SurfaceView restrictions (which, sadly, some don't).
2680 */
2681 Region transparentRegion;
2682
Mathias Agopianab028732010-03-16 16:41:46 -07002683
2684 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002685 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002686 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002687 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002688 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002689 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002690 if (!visibleRegion.isEmpty()) {
2691 // Remove the transparent area from the visible region
2692 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002693 if (tr.preserveRects()) {
2694 // transform the transparent region
2695 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002696 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002697 // transformation too complex, can't do the
2698 // transparent region optimization.
2699 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002700 }
Mathias Agopianab028732010-03-16 16:41:46 -07002701 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002702
Mathias Agopianab028732010-03-16 16:41:46 -07002703 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002704 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002705 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002706 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2707 // the opaque region is the layer's footprint
2708 opaqueRegion = visibleRegion;
2709 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002710 }
2711 }
2712
Robert Carre5f4f692018-01-12 13:12:28 -08002713 if (visibleRegion.isEmpty()) {
2714 layer->clearVisibilityRegions();
2715 return;
2716 }
2717
Mathias Agopianab028732010-03-16 16:41:46 -07002718 // Clip the covered region to the visible region
2719 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2720
2721 // Update aboveCoveredLayers for next (lower) layer
2722 aboveCoveredLayers.orSelf(visibleRegion);
2723
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002724 // subtract the opaque region covered by the layers above us
2725 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002726
2727 // compute this layer's dirty region
2728 if (layer->contentDirty) {
2729 // we need to invalidate the whole region
2730 dirty = visibleRegion;
2731 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002732 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002733 layer->contentDirty = false;
2734 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002735 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002736 * the exposed region consists of two components:
2737 * 1) what's VISIBLE now and was COVERED before
2738 * 2) what's EXPOSED now less what was EXPOSED before
2739 *
2740 * note that (1) is conservative, we start with the whole
2741 * visible region but only keep what used to be covered by
2742 * something -- which mean it may have been exposed.
2743 *
2744 * (2) handles areas that were not covered by anything but got
2745 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002746 */
Mathias Agopianab028732010-03-16 16:41:46 -07002747 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002748 const Region oldVisibleRegion = layer->visibleRegion;
2749 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002750 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2751 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002752 }
2753 dirty.subtractSelf(aboveOpaqueLayers);
2754
2755 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002756 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002757
Mathias Agopianab028732010-03-16 16:41:46 -07002758 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002759 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002760
Jesse Halla8026d22012-09-25 13:25:04 -07002761 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002762 layer->setVisibleRegion(visibleRegion);
2763 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002764 layer->setVisibleNonTransparentRegion(
2765 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002766 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002767
Mathias Agopian87baae12012-07-31 12:38:26 -07002768 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002769}
2770
Chia-I Wuab0c3192017-08-01 11:29:00 -07002771void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002772 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002773 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002774 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002775 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002776 }
2777 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002778}
2779
Dan Stoza6b9454d2014-11-07 16:00:59 -08002780bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002781{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002782 ALOGV("handlePageFlip");
2783
Brian Andersond6927fb2016-07-23 23:37:30 -07002784 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002785
Mathias Agopian4fec8732012-06-29 14:12:52 -07002786 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002787 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002788 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002789
2790 // Store the set of layers that need updates. This set must not change as
2791 // buffers are being latched, as this could result in a deadlock.
2792 // Example: Two producers share the same command stream and:
2793 // 1.) Layer 0 is latched
2794 // 2.) Layer 0 gets a new frame
2795 // 2.) Layer 1 gets a new frame
2796 // 3.) Layer 1 is latched.
2797 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2798 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002799 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002800 if (layer->hasQueuedFrame()) {
2801 frameQueued = true;
2802 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002803 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002804 } else {
2805 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002806 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002807 } else {
2808 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002809 }
Robert Carr2047fae2016-11-28 14:09:09 -08002810 });
2811
Dan Stoza9e56aa02015-11-02 13:00:03 -08002812 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002813 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002814 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002815 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002816 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002817 newDataLatched = true;
2818 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002819 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002820
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002821 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002822
2823 // If we will need to wake up at some time in the future to deal with a
2824 // queued frame that shouldn't be displayed during this vsync period, wake
2825 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002826 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002827 signalLayerUpdate();
2828 }
2829
2830 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002831 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002832}
2833
Mathias Agopianad456f92011-01-13 17:53:01 -08002834void SurfaceFlinger::invalidateHwcGeometry()
2835{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002836 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002837}
2838
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002839
Fabien Sanglard830b8472016-11-30 16:35:58 -08002840void SurfaceFlinger::doDisplayComposition(
2841 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002842 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002843{
Dan Stoza71433162014-02-04 16:22:36 -08002844 // We only need to actually compose the display if:
2845 // 1) It is being handled by hardware composer, which may need this to
2846 // keep its virtual display state machine in sync, or
2847 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002848 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002849 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002850 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002851 return;
2852 }
2853
Dan Stoza9e56aa02015-11-02 13:00:03 -08002854 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002855 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002856
2857 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002858 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002859}
2860
Chia-I Wub02087d2017-11-09 10:19:54 -08002861bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002862{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002863 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002864
Chia-I Wub02087d2017-11-09 10:19:54 -08002865 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002866 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002867 const auto hwcId = displayDevice->getHwcDisplayId();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002868 const bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002869 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002870
Chia-I Wu8e50e692018-05-04 10:12:37 -07002871 bool applyColorMatrix = false;
Peiyong Lin76dd77a2018-05-09 15:35:33 -07002872 bool needsLegacyColorMatrix = false;
2873 bool legacyColorMatrixApplied = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002874
Dan Stoza9e56aa02015-11-02 13:00:03 -08002875 if (hasClientComposition) {
2876 ALOGV("hasClientComposition");
2877
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002878 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002879 if (displayDevice->hasWideColorGamut()) {
2880 outputDataspace = displayDevice->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002881 }
2882 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002883 getBE().mRenderEngine->setDisplayMaxLuminance(
2884 displayDevice->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002885
Chia-I Wu8e50e692018-05-04 10:12:37 -07002886 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
2887 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2888 HWC2::Capability::SkipClientColorTransform);
2889
2890 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2891 if (applyColorMatrix) {
Peiyong Lin76dd77a2018-05-09 15:35:33 -07002892 getRenderEngine().setupColorTransform(mDrawingState.colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002893 }
2894
Chia-I Wubbb44462018-05-21 15:33:27 -07002895 needsLegacyColorMatrix =
Chia-I Wu0d711262018-05-21 15:19:35 -07002896 (displayDevice->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
Chia-I Wubbb44462018-05-21 15:33:27 -07002897 outputDataspace != Dataspace::UNKNOWN &&
2898 outputDataspace != Dataspace::SRGB);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002899
Chia-I Wu7f402902017-11-09 12:51:10 -08002900 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002901 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002902 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002903 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002904
2905 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002906 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002907 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2908 }
2909 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002910 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002911
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002912 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002913 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002914 // when using overlays, we assume a fully transparent framebuffer
2915 // NOTE: we could reduce how much we need to clear, for instance
2916 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002917 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002918 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002919 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002920 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002921 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002922 // we're left with the letterbox region
2923 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002924 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002925
2926 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002927 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002928
Mathias Agopianb9494d52012-04-18 02:28:45 -07002929 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002930 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002931 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002932 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002933 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002934 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002935
Dan Stoza9e56aa02015-11-02 13:00:03 -08002936 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002937 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002938 // scissor on the main display. It should never be needed
2939 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002940 const Rect& bounds(displayDevice->getBounds());
2941 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002942 if (scissor != bounds) {
2943 // scissor doesn't match the screen's dimensions, so we
2944 // need to clear everything outside of it and enable
2945 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002946
Mathias Agopianf45c5102012-10-24 16:29:17 -07002947 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002948 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002949 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002950 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002951 }
2952 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002953 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002954
Mathias Agopian85d751c2012-08-29 16:59:24 -07002955 /*
2956 * and then, render the layers targeted at the framebuffer
2957 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002958
Dan Stoza9e56aa02015-11-02 13:00:03 -08002959 ALOGV("Rendering client layers");
2960 const Transform& displayTransform = displayDevice->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002961 bool firstLayer = true;
2962 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2963 const Region clip(bounds.intersect(
2964 displayTransform.transform(layer->visibleRegion)));
2965 ALOGV("Layer: %s", layer->getName().string());
2966 ALOGV(" Composition type: %s",
2967 to_string(layer->getCompositionType(hwcId)).c_str());
2968 if (!clip.isEmpty()) {
2969 switch (layer->getCompositionType(hwcId)) {
2970 case HWC2::Composition::Cursor:
2971 case HWC2::Composition::Device:
2972 case HWC2::Composition::Sideband:
2973 case HWC2::Composition::SolidColor: {
2974 const Layer::State& state(layer->getDrawingState());
2975 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2976 layer->isOpaque(state) && (state.color.a == 1.0f)
2977 && hasClientComposition) {
2978 // never clear the very first layer since we're
2979 // guaranteed the FB is already cleared
2980 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002981 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002982 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002983 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002984 case HWC2::Composition::Client: {
Chia-I Wu8e50e692018-05-04 10:12:37 -07002985 // switch color matrices lazily
Peiyong Lin76dd77a2018-05-09 15:35:33 -07002986 if (layer->isLegacyDataSpace() && needsLegacyColorMatrix) {
2987 if (!legacyColorMatrixApplied) {
2988 getRenderEngine().setSaturationMatrix(mLegacySrgbSaturationMatrix);
2989 legacyColorMatrixApplied = true;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002990 }
Peiyong Lin76dd77a2018-05-09 15:35:33 -07002991 } else if (legacyColorMatrixApplied) {
2992 getRenderEngine().setSaturationMatrix(mat4());
2993 legacyColorMatrixApplied = false;
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002994 }
Chia-I Wu8e50e692018-05-04 10:12:37 -07002995
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002996 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002997 break;
2998 }
2999 default:
3000 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003001 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003002 } else {
3003 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003004 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003005 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003006 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003007
Peiyong Lin76dd77a2018-05-09 15:35:33 -07003008 if (applyColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003009 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003010 }
Peiyong Lin76dd77a2018-05-09 15:35:33 -07003011 if (needsLegacyColorMatrix && legacyColorMatrixApplied) {
3012 getRenderEngine().setSaturationMatrix(mat4());
3013 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003014
Mathias Agopianf45c5102012-10-24 16:29:17 -07003015 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003016 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003017 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003018}
3019
Fabien Sanglard830b8472016-11-30 16:35:58 -08003020void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
3021 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003022 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003023 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003024}
3025
Dan Stoza7d89d062015-04-30 13:29:25 -07003026status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003027 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003028 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003029 const sp<Layer>& lbc,
3030 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003031{
Dan Stoza7d89d062015-04-30 13:29:25 -07003032 // add this layer to the current state list
3033 {
3034 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003035 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003036 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3037 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003038 return NO_MEMORY;
3039 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003040 if (parent == nullptr) {
3041 mCurrentState.layersSortedByZ.add(lbc);
3042 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003043 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003044 ALOGE("addClientLayer called with a removed parent");
3045 return NAME_NOT_FOUND;
3046 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003047 parent->addChild(lbc);
3048 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003049
Yiwei Zhang243b3782018-05-15 17:40:04 -07003050 if (gbc != nullptr) {
3051 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3052 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3053 mMaxGraphicBufferProducerListSize,
3054 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3055 mGraphicBufferProducerList.size(),
3056 mMaxGraphicBufferProducerListSize, mNumLayers);
3057 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003058 mLayersAdded = true;
3059 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003060 }
3061
Mathias Agopian96f08192010-06-02 23:28:45 -07003062 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003063 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003064
Dan Stoza7d89d062015-04-30 13:29:25 -07003065 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003066}
3067
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003068status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003069 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003070 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3071}
Robert Carr7f9b8992017-03-10 11:08:39 -08003072
chaviwca27f252018-02-06 16:46:39 -08003073status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3074 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003075 if (layer->isPendingRemoval()) {
3076 return NO_ERROR;
3077 }
3078
Robert Carr1f0a16a2016-10-24 16:27:39 -07003079 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003080 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003081 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003082 if (topLevelOnly) {
3083 return NO_ERROR;
3084 }
3085
Chia-I Wu98f1c102017-05-30 14:54:08 -07003086 sp<Layer> ancestor = p;
3087 while (ancestor->getParent() != nullptr) {
3088 ancestor = ancestor->getParent();
3089 }
3090 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3091 ALOGE("removeLayer called with a layer whose parent has been removed");
3092 return NAME_NOT_FOUND;
3093 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003094
3095 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003096 } else {
3097 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003098 }
3099
Robert Carr136e2f62017-02-08 17:54:29 -08003100 // As a matter of normal operation, the LayerCleaner will produce a second
3101 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3102 // so we will succeed in promoting it, but it's already been removed
3103 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3104 // otherwise something has gone wrong and we are leaking the layer.
3105 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003106 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3107 layer->getName().string(),
3108 (p != nullptr) ? p->getName().string() : "no-parent");
3109 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003110 } else if (index < 0) {
3111 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003112 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003113
Chia-I Wuc6657022017-08-15 11:18:17 -07003114 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003115 mLayersPendingRemoval.add(layer);
3116 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003117 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003118 setTransactionFlags(eTransactionNeeded);
3119 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003120}
3121
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003122uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003123 return android_atomic_release_load(&mTransactionFlags);
3124}
3125
Mathias Agopian3f844832013-08-07 21:24:32 -07003126uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003127 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3128}
3129
Mathias Agopian3f844832013-08-07 21:24:32 -07003130uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza2713c302018-03-28 17:07:36 -07003131 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3132}
3133
3134uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3135 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003136 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza2713c302018-03-28 17:07:36 -07003137 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003138 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003139 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003140 }
3141 return old;
3142}
3143
chaviwca27f252018-02-06 16:46:39 -08003144bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3145 for (const ComposerState& state : states) {
3146 // Here we need to check that the interface we're given is indeed
3147 // one of our own. A malicious client could give us a nullptr
3148 // IInterface, or one of its own or even one of our own but a
3149 // different type. All these situations would cause us to crash.
3150 if (state.client == nullptr) {
3151 return true;
3152 }
3153
3154 sp<IBinder> binder = IInterface::asBinder(state.client);
3155 if (binder == nullptr) {
3156 return true;
3157 }
3158
3159 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3160 return true;
3161 }
3162 }
3163 return false;
3164}
3165
Mathias Agopian8b33f032012-07-24 20:43:54 -07003166void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003167 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003168 const Vector<DisplayState>& displays,
3169 uint32_t flags)
3170{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003171 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003172 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003173 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003174
chaviwca27f252018-02-06 16:46:39 -08003175 if (containsAnyInvalidClientState(states)) {
3176 return;
3177 }
3178
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003179 if (flags & eAnimation) {
3180 // For window updates that are part of an animation we must wait for
3181 // previous animation "frames" to be handled.
3182 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003183 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003184 if (CC_UNLIKELY(err != NO_ERROR)) {
3185 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003186 // caller after a few seconds.
3187 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3188 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003189 mAnimTransactionPending = false;
3190 break;
3191 }
3192 }
3193 }
3194
chaviwca27f252018-02-06 16:46:39 -08003195 for (const DisplayState& display : displays) {
3196 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003197 }
3198
chaviwca27f252018-02-06 16:46:39 -08003199 for (const ComposerState& state : states) {
3200 transactionFlags |= setClientStateLocked(state);
3201 }
3202
3203 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3204 // as destroyed should only occur after setting all other states. This is to allow for a
3205 // child re-parent to happen before marking its original parent as destroyed (which would
3206 // then mark the child as destroyed).
3207 for (const ComposerState& state : states) {
3208 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003209 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003210
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003211 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3212 // anyway. This can be used as a flush mechanism for previous async transactions.
3213 // Empty animation transaction can be used to simulate back-pressure, so also force a
3214 // transaction for empty animation transactions.
3215 if (transactionFlags == 0 &&
3216 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003217 transactionFlags = eTransactionNeeded;
3218 }
3219
Mathias Agopian386aa982011-11-07 21:58:03 -08003220 if (transactionFlags) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003221 if (mInterceptor->isEnabled()) {
3222 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003223 }
Irvel468051e2016-06-13 16:44:44 -07003224
Mathias Agopian386aa982011-11-07 21:58:03 -08003225 // this triggers the transaction
Dan Stoza2713c302018-03-28 17:07:36 -07003226 const auto start = (flags & eEarlyWakeup)
3227 ? VSyncModulator::TransactionStart::EARLY
3228 : VSyncModulator::TransactionStart::NORMAL;
3229 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003230
3231 // if this is a synchronous transaction, wait for it to take effect
3232 // before returning.
3233 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003234 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003235 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003236 if (flags & eAnimation) {
3237 mAnimTransactionPending = true;
3238 }
3239 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003240 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3241 if (CC_UNLIKELY(err != NO_ERROR)) {
3242 // just in case something goes wrong in SF, return to the
3243 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003244 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3245 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003246 break;
3247 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003248 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003249 }
3250}
3251
Mathias Agopiane57f2922012-08-09 16:29:12 -07003252uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3253{
Jesse Hall9a143922012-10-04 16:29:19 -07003254 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3255 if (dpyIdx < 0)
3256 return 0;
3257
Mathias Agopiane57f2922012-08-09 16:29:12 -07003258 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003259 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003260 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003261 const uint32_t what = s.what;
3262 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003263 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003264 disp.surface = s.surface;
3265 flags |= eDisplayTransactionNeeded;
3266 }
3267 }
3268 if (what & DisplayState::eLayerStackChanged) {
3269 if (disp.layerStack != s.layerStack) {
3270 disp.layerStack = s.layerStack;
3271 flags |= eDisplayTransactionNeeded;
3272 }
3273 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003274 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003275 if (disp.orientation != s.orientation) {
3276 disp.orientation = s.orientation;
3277 flags |= eDisplayTransactionNeeded;
3278 }
3279 if (disp.frame != s.frame) {
3280 disp.frame = s.frame;
3281 flags |= eDisplayTransactionNeeded;
3282 }
3283 if (disp.viewport != s.viewport) {
3284 disp.viewport = s.viewport;
3285 flags |= eDisplayTransactionNeeded;
3286 }
3287 }
Michael Lentine47e45402014-07-18 15:34:25 -07003288 if (what & DisplayState::eDisplaySizeChanged) {
3289 if (disp.width != s.width) {
3290 disp.width = s.width;
3291 flags |= eDisplayTransactionNeeded;
3292 }
3293 if (disp.height != s.height) {
3294 disp.height = s.height;
3295 flags |= eDisplayTransactionNeeded;
3296 }
3297 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003298 }
3299 return flags;
3300}
3301
chaviwca27f252018-02-06 16:46:39 -08003302uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3303 const layer_state_t& s = composerState.state;
3304 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3305
Mathias Agopian13127d82013-03-05 17:47:11 -08003306 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003307 if (layer == nullptr) {
3308 return 0;
3309 }
3310
3311 if (layer->isPendingRemoval()) {
3312 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3313 return 0;
3314 }
3315
3316 uint32_t flags = 0;
3317
3318 const uint32_t what = s.what;
3319 bool geometryAppliesWithResize =
3320 what & layer_state_t::eGeometryAppliesWithResize;
3321 if (what & layer_state_t::ePositionChanged) {
3322 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3323 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003324 }
chaviw8b3871a2017-11-01 17:41:01 -07003325 }
3326 if (what & layer_state_t::eLayerChanged) {
3327 // NOTE: index needs to be calculated before we update the state
3328 const auto& p = layer->getParent();
3329 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003330 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003331 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003332 mCurrentState.layersSortedByZ.removeAt(idx);
3333 mCurrentState.layersSortedByZ.add(layer);
3334 // we need traversal (state changed)
3335 // AND transaction (list changed)
3336 flags |= eTransactionNeeded|eTraversalNeeded;
3337 }
chaviw8b3871a2017-11-01 17:41:01 -07003338 } else {
3339 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003340 flags |= eTransactionNeeded|eTraversalNeeded;
3341 }
3342 }
chaviw8b3871a2017-11-01 17:41:01 -07003343 }
3344 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003345 // NOTE: index needs to be calculated before we update the state
3346 const auto& p = layer->getParent();
3347 if (p == nullptr) {
3348 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3349 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3350 mCurrentState.layersSortedByZ.removeAt(idx);
3351 mCurrentState.layersSortedByZ.add(layer);
3352 // we need traversal (state changed)
3353 // AND transaction (list changed)
3354 flags |= eTransactionNeeded|eTraversalNeeded;
3355 }
3356 } else {
3357 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3358 flags |= eTransactionNeeded|eTraversalNeeded;
3359 }
chaviw8b3871a2017-11-01 17:41:01 -07003360 }
3361 }
3362 if (what & layer_state_t::eSizeChanged) {
3363 if (layer->setSize(s.w, s.h)) {
3364 flags |= eTraversalNeeded;
3365 }
3366 }
3367 if (what & layer_state_t::eAlphaChanged) {
3368 if (layer->setAlpha(s.alpha))
3369 flags |= eTraversalNeeded;
3370 }
3371 if (what & layer_state_t::eColorChanged) {
3372 if (layer->setColor(s.color))
3373 flags |= eTraversalNeeded;
3374 }
3375 if (what & layer_state_t::eMatrixChanged) {
3376 if (layer->setMatrix(s.matrix))
3377 flags |= eTraversalNeeded;
3378 }
3379 if (what & layer_state_t::eTransparentRegionChanged) {
3380 if (layer->setTransparentRegionHint(s.transparentRegion))
3381 flags |= eTraversalNeeded;
3382 }
3383 if (what & layer_state_t::eFlagsChanged) {
3384 if (layer->setFlags(s.flags, s.mask))
3385 flags |= eTraversalNeeded;
3386 }
3387 if (what & layer_state_t::eCropChanged) {
3388 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3389 flags |= eTraversalNeeded;
3390 }
3391 if (what & layer_state_t::eFinalCropChanged) {
3392 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3393 flags |= eTraversalNeeded;
3394 }
3395 if (what & layer_state_t::eLayerStackChanged) {
3396 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3397 // We only allow setting layer stacks for top level layers,
3398 // everything else inherits layer stack from its parent.
3399 if (layer->hasParent()) {
3400 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3401 layer->getName().string());
3402 } else if (idx < 0) {
3403 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3404 "that also does not appear in the top level layer list. Something"
3405 " has gone wrong.", layer->getName().string());
3406 } else if (layer->setLayerStack(s.layerStack)) {
3407 mCurrentState.layersSortedByZ.removeAt(idx);
3408 mCurrentState.layersSortedByZ.add(layer);
3409 // we need traversal (state changed)
3410 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003411 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003412 }
3413 }
3414 if (what & layer_state_t::eDeferTransaction) {
3415 if (s.barrierHandle != nullptr) {
3416 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3417 } else if (s.barrierGbp != nullptr) {
3418 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3419 if (authenticateSurfaceTextureLocked(gbp)) {
3420 const auto& otherLayer =
3421 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3422 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3423 } else {
3424 ALOGE("Attempt to defer transaction to to an"
3425 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003426 }
3427 }
chaviw8b3871a2017-11-01 17:41:01 -07003428 // We don't trigger a traversal here because if no other state is
3429 // changed, we don't want this to cause any more work
3430 }
3431 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003432 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003433 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003434 if (!hadParent) {
3435 mCurrentState.layersSortedByZ.remove(layer);
3436 }
chaviw8b3871a2017-11-01 17:41:01 -07003437 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003438 }
chaviw8b3871a2017-11-01 17:41:01 -07003439 }
3440 if (what & layer_state_t::eReparentChildren) {
3441 if (layer->reparentChildren(s.reparentHandle)) {
3442 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003443 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003444 }
chaviw8b3871a2017-11-01 17:41:01 -07003445 if (what & layer_state_t::eDetachChildren) {
3446 layer->detachChildren();
3447 }
3448 if (what & layer_state_t::eOverrideScalingModeChanged) {
3449 layer->setOverrideScalingMode(s.overrideScalingMode);
3450 // We don't trigger a traversal here because if no other state is
3451 // changed, we don't want this to cause any more work
3452 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003453 return flags;
3454}
3455
chaviwca27f252018-02-06 16:46:39 -08003456void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3457 const layer_state_t& state = composerState.state;
3458 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3459
3460 sp<Layer> layer(client->getLayerUser(state.surface));
3461 if (layer == nullptr) {
3462 return;
3463 }
3464
3465 if (layer->isPendingRemoval()) {
3466 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3467 return;
3468 }
3469
3470 if (state.what & layer_state_t::eDestroySurface) {
3471 removeLayerLocked(mStateLock, layer);
3472 }
3473}
3474
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003475status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003476 const String8& name,
3477 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003478 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliuccd34842018-03-14 12:26:23 -07003479 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003480 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003481{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003482 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003483 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003484 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003485 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003486 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003487
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003488 status_t result = NO_ERROR;
3489
3490 sp<Layer> layer;
3491
Cody Northropbc755282017-03-31 12:00:08 -06003492 String8 uniqueName = getUniqueLayerName(name);
3493
Mathias Agopian3165cc22012-08-08 19:42:09 -07003494 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3495 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003496 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003497 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003498 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003499
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003500 break;
chaviw13fdc492017-06-27 12:40:18 -07003501 case ISurfaceComposerClient::eFXSurfaceColor:
3502 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003503 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003504 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003505 break;
3506 default:
3507 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003508 break;
3509 }
3510
Dan Stoza7d89d062015-04-30 13:29:25 -07003511 if (result != NO_ERROR) {
3512 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003513 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003514
Chia-I Wuab0c3192017-08-01 11:29:00 -07003515 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3516 // TODO b/64227542
3517 if (windowType == 441731) {
3518 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3519 layer->setPrimaryDisplayOnly();
3520 }
3521
Albert Chaulk479c60c2017-01-27 14:21:34 -05003522 layer->setInfo(windowType, ownerUid);
3523
Robert Carr1f0a16a2016-10-24 16:27:39 -07003524 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003525 if (result != NO_ERROR) {
3526 return result;
3527 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003528 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003529
3530 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003531 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003532}
3533
Cody Northropbc755282017-03-31 12:00:08 -06003534String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3535{
3536 bool matchFound = true;
3537 uint32_t dupeCounter = 0;
3538
3539 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3540 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3541
3542 // Loop over layers until we're sure there is no matching name
3543 while (matchFound) {
3544 matchFound = false;
3545 mDrawingState.traverseInZOrder([&](Layer* layer) {
3546 if (layer->getName() == uniqueName) {
3547 matchFound = true;
3548 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3549 }
3550 });
3551 }
3552
3553 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3554
3555 return uniqueName;
3556}
3557
David Sodman0c69cad2017-08-21 12:12:51 -07003558status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003559 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3560 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003561{
3562 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003563 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003564 case PIXEL_FORMAT_TRANSPARENT:
3565 case PIXEL_FORMAT_TRANSLUCENT:
3566 format = PIXEL_FORMAT_RGBA_8888;
3567 break;
3568 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003569 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003570 break;
3571 }
3572
David Sodman0c69cad2017-08-21 12:12:51 -07003573 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3574 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003575 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003576 *handle = layer->getHandle();
3577 *gbp = layer->getProducer();
3578 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003579 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003580
David Sodman0c69cad2017-08-21 12:12:51 -07003581 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003582 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003583}
3584
chaviw13fdc492017-06-27 12:40:18 -07003585status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003586 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003587 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003588{
chaviw13fdc492017-06-27 12:40:18 -07003589 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003590 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003591 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003592}
3593
Mathias Agopianac9fa422013-02-11 16:40:36 -08003594status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003595{
Robert Carr9524cb32017-02-13 11:32:32 -08003596 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003597 status_t err = NO_ERROR;
3598 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003599 if (l != nullptr) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003600 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003601 err = removeLayer(l);
3602 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3603 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003604 }
3605 return err;
3606}
3607
Mathias Agopian13127d82013-03-05 17:47:11 -08003608status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003609{
Mathias Agopian67106042013-03-14 19:18:13 -07003610 // called by ~LayerCleaner() when all references to the IBinder (handle)
3611 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003612 sp<Layer> l = layer.promote();
3613 if (l == nullptr) {
3614 // The layer has already been removed, carry on
3615 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003616 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003617 // If we have a parent, then we can continue to live as long as it does.
3618 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003619}
3620
Mathias Agopianb60314a2012-04-10 22:09:54 -07003621// ---------------------------------------------------------------------------
3622
Andy McFadden13a082e2012-08-24 10:16:42 -07003623void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003624 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003625 Vector<ComposerState> state;
3626 Vector<DisplayState> displays;
3627 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003628 d.what = DisplayState::eDisplayProjectionChanged |
3629 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003630 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003631 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003632 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003633 d.frame.makeInvalid();
3634 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003635 d.width = 0;
3636 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003637 displays.add(d);
3638 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003639 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3640 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003641
David Sodman105b7dc2017-11-04 20:28:14 -07003642 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003643 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003644 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003645
Brian Andersond0010582017-03-07 13:20:31 -08003646 // Use phase of 0 since phase is not known.
3647 // Use latency of 0, which will snap to the ideal latency.
3648 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003649}
3650
3651void SurfaceFlinger::initializeDisplays() {
3652 class MessageScreenInitialized : public MessageBase {
3653 SurfaceFlinger* flinger;
3654 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003655 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003656 virtual bool handler() {
3657 flinger->onInitializeDisplays();
3658 return true;
3659 }
3660 };
3661 sp<MessageBase> msg = new MessageScreenInitialized(this);
3662 postMessageAsync(msg); // we may be called from main thread, use async message
3663}
3664
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003665void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003666 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003667 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3668 this);
3669 int32_t type = hw->getDisplayType();
3670 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003671
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003672 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003673 return;
3674 }
3675
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003676 hw->setPowerMode(mode);
3677 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3678 ALOGW("Trying to set power mode for virtual display");
3679 return;
3680 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003681
Lloyd Pique4d234852018-01-22 17:21:36 -08003682 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003683 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003684 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3685 if (idx < 0) {
3686 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3687 return;
3688 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003689 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003690 }
3691
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003692 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003693 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003694 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003695 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3696 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003697 // FIXME: eventthread only knows about the main display right now
3698 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003699 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003700 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003701
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003702 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003703 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003704 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003705
3706 struct sched_param param = {0};
3707 param.sched_priority = 1;
3708 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3709 ALOGW("Couldn't set SCHED_FIFO on display on");
3710 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003711 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003712 // Turn off the display
3713 struct sched_param param = {0};
3714 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3715 ALOGW("Couldn't set SCHED_OTHER on display off");
3716 }
3717
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003718 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3719 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003720 disableHardwareVsync(true); // also cancels any in-progress resync
3721
Mathias Agopiancde87a32012-09-13 14:09:01 -07003722 // FIXME: eventthread only knows about the main display right now
3723 mEventThread->onScreenReleased();
3724 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003725
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003726 getHwComposer().setPowerMode(type, mode);
3727 mVisibleRegionsDirty = true;
3728 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003729 } else if (mode == HWC_POWER_MODE_DOZE ||
3730 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003731 // Update display while dozing
3732 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003733 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3734 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003735 // FIXME: eventthread only knows about the main display right now
3736 mEventThread->onScreenAcquired();
3737 resyncToHardwareVsync(true);
3738 }
3739 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3740 // Leave display going to doze
3741 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3742 disableHardwareVsync(true); // also cancels any in-progress resync
3743 // FIXME: eventthread only knows about the main display right now
3744 mEventThread->onScreenReleased();
3745 }
3746 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003747 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003748 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003749 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003750 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003751 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003752}
3753
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003754void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3755 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003756 SurfaceFlinger& mFlinger;
3757 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003758 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003759 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003760 MessageSetPowerMode(SurfaceFlinger& flinger,
3761 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3762 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003763 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003764 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003765 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003766 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003767 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003768 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003769 ALOGW("Attempt to set power mode = %d for virtual display",
3770 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003771 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003772 mFlinger.setPowerModeInternal(
3773 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003774 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003775 return true;
3776 }
3777 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003778 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003779 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003780}
3781
3782// ---------------------------------------------------------------------------
3783
Lloyd Pique755e3192018-01-31 16:46:15 -08003784status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3785 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003786 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003787
Mathias Agopianbd115332013-04-18 16:41:04 -07003788 IPCThreadState* ipc = IPCThreadState::self();
3789 const int pid = ipc->getCallingPid();
3790 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003791
Mathias Agopianbd115332013-04-18 16:41:04 -07003792 if ((uid != AID_SHELL) &&
3793 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003794 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003795 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003796 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003797 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003798 // (this would indicate SF is stuck, but we want to be able to
3799 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003800 status_t err = mStateLock.timedLock(s2ns(1));
3801 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003802 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003803 result.appendFormat(
3804 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3805 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003806 }
3807
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003808 bool dumpAll = true;
3809 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003810 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003811
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003812 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003813 if ((index < numArgs) &&
3814 (args[index] == String16("--list"))) {
3815 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003816 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003817 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003818 }
3819
3820 if ((index < numArgs) &&
3821 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003822 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003823 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003824 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003825 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003826
3827 if ((index < numArgs) &&
3828 (args[index] == String16("--latency-clear"))) {
3829 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003830 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003831 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003832 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003833
3834 if ((index < numArgs) &&
3835 (args[index] == String16("--dispsync"))) {
3836 index++;
3837 mPrimaryDispSync.dump(result);
3838 dumpAll = false;
3839 }
Dan Stozab90cf072015-03-05 11:05:59 -08003840
3841 if ((index < numArgs) &&
3842 (args[index] == String16("--static-screen"))) {
3843 index++;
3844 dumpStaticScreenStats(result);
3845 dumpAll = false;
3846 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003847
3848 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003849 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003850 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003851 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003852 dumpAll = false;
3853 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003854
3855 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3856 index++;
3857 dumpWideColorInfo(result);
3858 dumpAll = false;
3859 }
Yiwei Zhang068e31b2018-02-21 13:02:45 -08003860
3861 if ((index < numArgs) &&
3862 (args[index] == String16("--enable-layer-stats"))) {
3863 index++;
3864 mLayerStats.enable();
3865 dumpAll = false;
3866 }
3867
3868 if ((index < numArgs) &&
3869 (args[index] == String16("--disable-layer-stats"))) {
3870 index++;
3871 mLayerStats.disable();
3872 dumpAll = false;
3873 }
3874
3875 if ((index < numArgs) &&
3876 (args[index] == String16("--clear-layer-stats"))) {
3877 index++;
3878 mLayerStats.clear();
3879 dumpAll = false;
3880 }
3881
3882 if ((index < numArgs) &&
3883 (args[index] == String16("--dump-layer-stats"))) {
3884 index++;
3885 mLayerStats.dump(result);
3886 dumpAll = false;
3887 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -07003888
3889 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3890 index++;
3891 mTimeStats.parseArgs(asProto, args, index, result);
3892 dumpAll = false;
3893 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003894 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003895
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003896 if (dumpAll) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -07003897 if (asProto) {
3898 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3899 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3900 } else {
3901 dumpAllLocked(args, index, result);
3902 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08003903 }
3904
Mathias Agopian9795c422009-08-26 16:36:26 -07003905 if (locked) {
3906 mStateLock.unlock();
3907 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003908 }
3909 write(fd, result.string(), result.size());
3910 return NO_ERROR;
3911}
3912
Dan Stozac7014012014-02-14 15:03:43 -08003913void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3914 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003915{
Robert Carr2047fae2016-11-28 14:09:09 -08003916 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003917 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003918 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003919}
3920
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003921void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003922 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003923{
3924 String8 name;
3925 if (index < args.size()) {
3926 name = String8(args[index]);
3927 index++;
3928 }
3929
David Sodman105b7dc2017-11-04 20:28:14 -07003930 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003931 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003932 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003933
3934 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003935 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003936 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003937 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003938 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003939 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003940 }
Robert Carr2047fae2016-11-28 14:09:09 -08003941 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003942 }
3943}
3944
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003945void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003946 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003947{
3948 String8 name;
3949 if (index < args.size()) {
3950 name = String8(args[index]);
3951 index++;
3952 }
3953
Robert Carr2047fae2016-11-28 14:09:09 -08003954 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003955 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003956 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003957 }
Robert Carr2047fae2016-11-28 14:09:09 -08003958 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003959
Svetoslavd85084b2014-03-20 10:28:31 -07003960 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003961}
3962
Jamie Gennis6547ff42013-07-16 20:12:42 -07003963// This should only be called from the main thread. Otherwise it would need
3964// the lock and should use mCurrentState rather than mDrawingState.
3965void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003966 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003967 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003968 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003969
3970 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3971}
3972
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003973void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003974{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003975 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003976
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003977 if (isLayerTripleBufferingDisabled())
3978 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003979
3980 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003981 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003982 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003983 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003984 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3985 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003986 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003987}
3988
Dan Stozab90cf072015-03-05 11:05:59 -08003989void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3990{
3991 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003992 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3993 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003994 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003995 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08003996 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3997 b + 1, bucketTimeSec, percent);
3998 }
David Sodman4a36e932017-11-07 14:29:47 -08003999 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004000 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004001 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004002 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004003 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004004}
4005
Dan Stozae77c7662016-05-13 11:37:28 -07004006void SurfaceFlinger::recordBufferingStats(const char* layerName,
4007 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004008 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4009 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004010 for (const auto& segment : history) {
4011 if (!segment.usedThirdBuffer) {
4012 stats.twoBufferTime += segment.totalTime;
4013 }
4014 if (segment.occupancyAverage < 1.0f) {
4015 stats.doubleBufferedTime += segment.totalTime;
4016 } else if (segment.occupancyAverage < 2.0f) {
4017 stats.tripleBufferedTime += segment.totalTime;
4018 }
4019 ++stats.numSegments;
4020 stats.totalTime += segment.totalTime;
4021 }
4022}
4023
Brian Andersond6927fb2016-07-23 23:37:30 -07004024void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4025 result.appendFormat("Layer frame timestamps:\n");
4026
4027 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4028 const size_t count = currentLayers.size();
4029 for (size_t i=0 ; i<count ; i++) {
4030 currentLayers[i]->dumpFrameEvents(result);
4031 }
4032}
4033
Dan Stozae77c7662016-05-13 11:37:28 -07004034void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4035 result.append("Buffering stats:\n");
4036 result.append(" [Layer name] <Active time> <Two buffer> "
4037 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004038 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004039 typedef std::tuple<std::string, float, float, float> BufferTuple;
4040 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004041 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004042 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004043 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004044 if (stats.numSegments == 0) {
4045 continue;
4046 }
4047 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4048 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4049 stats.totalTime;
4050 float doubleBufferRatio = static_cast<float>(
4051 stats.doubleBufferedTime) / stats.totalTime;
4052 float tripleBufferRatio = static_cast<float>(
4053 stats.tripleBufferedTime) / stats.totalTime;
4054 sorted.insert({activeTime, {name, twoBufferRatio,
4055 doubleBufferRatio, tripleBufferRatio}});
4056 }
4057 for (const auto& sortedPair : sorted) {
4058 float activeTime = sortedPair.first;
4059 const BufferTuple& values = sortedPair.second;
4060 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4061 std::get<0>(values).c_str(), activeTime,
4062 std::get<1>(values), std::get<2>(values),
4063 std::get<3>(values));
4064 }
4065 result.append("\n");
4066}
4067
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004068void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4069 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Chia-I Wu0d711262018-05-21 15:19:35 -07004070 result.appendFormat("DisplayColorSetting: %s\n",
4071 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004072
4073 // TODO: print out if wide-color mode is active or not
4074
4075 for (size_t d = 0; d < mDisplays.size(); d++) {
4076 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4077 int32_t hwcId = displayDevice->getHwcDisplayId();
4078 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4079 continue;
4080 }
4081
4082 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004083 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004084 for (auto&& mode : modes) {
4085 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4086 }
4087
Peiyong Lina52f0292018-03-14 17:26:31 -07004088 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004089 result.appendFormat(" Current color mode: %s (%d)\n",
4090 decodeColorMode(currentMode).c_str(), currentMode);
4091 }
4092 result.append("\n");
4093}
4094
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004095LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004096 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004097 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4098 const State& state = useDrawing ? mDrawingState : mCurrentState;
4099 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004100 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004101 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004102 });
4103
4104 return layersProto;
4105}
4106
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004107LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4108 LayersProto layersProto;
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004109 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004110
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004111 SizeProto* resolution = layersProto.mutable_resolution();
4112 resolution->set_w(displayDevice->getWidth());
4113 resolution->set_h(displayDevice->getHeight());
4114
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004115 layersProto.set_color_mode(decodeColorMode(displayDevice->getActiveColorMode()));
4116 layersProto.set_color_transform(decodeColorTransform(displayDevice->getColorTransform()));
4117 layersProto.set_global_transform(
4118 static_cast<int32_t>(displayDevice->getOrientationTransform()));
4119
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004120 mDrawingState.traverseInZOrder([&](Layer* layer) {
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004121 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004122 LayerProto* layerProto = layersProto.add_layers();
4123 layer->writeToProto(layerProto, hwcId);
4124 }
4125 });
4126
4127 return layersProto;
4128}
4129
Mathias Agopian74d211a2013-04-22 16:55:35 +02004130void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4131 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004132{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004133 bool colorize = false;
4134 if (index < args.size()
4135 && (args[index] == String16("--color"))) {
4136 colorize = true;
4137 index++;
4138 }
4139
4140 Colorizer colorizer(colorize);
4141
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004142 // figure out if we're stuck somewhere
4143 const nsecs_t now = systemTime();
4144 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4145 const nsecs_t inTransaction(mDebugInTransaction);
4146 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4147 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4148
4149 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004150 * Dump library configuration.
4151 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004152
4153 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004154 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004155 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004156 appendSfConfigString(result);
4157 appendUiConfigString(result);
4158 appendGuiConfigString(result);
4159 result.append("\n");
4160
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004161 result.append("\nWide-Color information:\n");
4162 dumpWideColorInfo(result);
4163
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004164 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004165 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004166 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004167 result.append(SyncFeatures::getInstance().toString());
4168 result.append("\n");
4169
David Sodman105b7dc2017-11-04 20:28:14 -07004170 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004171
Andy McFadden41d67d72014-04-25 16:58:34 -07004172 colorizer.bold(result);
4173 result.append("DispSync configuration: ");
4174 colorizer.reset(result);
Dan Stoza2713c302018-03-28 17:07:36 -07004175 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, early sf phase %" PRId64
4176 " ns, present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4177 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, mVsyncModulator.getEarlyPhaseOffset(),
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004178 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004179 result.append("\n");
4180
Dan Stozab90cf072015-03-05 11:05:59 -08004181 // Dump static screen stats
4182 result.append("\n");
4183 dumpStaticScreenStats(result);
4184 result.append("\n");
4185
Dan Stozae77c7662016-05-13 11:37:28 -07004186 dumpBufferingStats(result);
4187
Andy McFadden4803b742012-09-24 19:07:20 -07004188 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004189 * Dump the visible layer list
4190 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004191 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004192 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004193 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4194 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004195 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004196
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004197 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004198 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7794ec12018-03-14 13:28:39 -07004199 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004200 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004201
4202 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004203 * Dump Display state
4204 */
4205
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004206 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004207 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004208 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004209 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4210 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004211 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004212 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004213 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004214
4215 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004216 * Dump SurfaceFlinger global state
4217 */
4218
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004219 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004220 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004221 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004222
Mathias Agopian888c8222012-08-04 21:10:38 -07004223 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004224 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004225
David Sodmanbc815282017-11-05 18:57:52 -08004226 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004227
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004228 if (hw) {
4229 hw->undefinedRegion.dump(result, "undefinedRegion");
4230 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4231 hw->getOrientation(), hw->isDisplayOn());
4232 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004233 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004234 " last eglSwapBuffers() time: %f us\n"
4235 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004236 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004237 " refresh-rate : %f fps\n"
4238 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004239 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004240 " gpu_to_cpu_unsupported : %d\n"
4241 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004242 mLastSwapBufferTime/1000.0,
4243 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004244 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004245 1e9 / activeConfig->getVsyncPeriod(),
4246 activeConfig->getDpiX(),
4247 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004248 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004249
Mathias Agopian74d211a2013-04-22 16:55:35 +02004250 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004251 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004252
Mathias Agopian74d211a2013-04-22 16:55:35 +02004253 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004254 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004255
4256 /*
4257 * VSYNC state
4258 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004259 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004260 result.append("\n");
4261
4262 /*
4263 * HWC layer minidump
4264 */
4265 for (size_t d = 0; d < mDisplays.size(); d++) {
4266 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4267 int32_t hwcId = displayDevice->getHwcDisplayId();
4268 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4269 continue;
4270 }
4271
4272 result.appendFormat("Display %d HWC layers:\n", hwcId);
4273 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004274 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004275 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004276 });
Dan Stozae22aec72016-08-01 13:20:59 -07004277 result.append("\n");
4278 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004279
4280 /*
4281 * Dump HWComposer state
4282 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004283 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004284 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004285 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004286 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004287 result.appendFormat(" h/w composer %s\n",
4288 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004289 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004290
4291 /*
4292 * Dump gralloc state
4293 */
4294 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4295 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004296
4297 /*
4298 * Dump VrFlinger state if in use.
4299 */
4300 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4301 result.append("VrFlinger state:\n");
4302 result.append(mVrFlinger->Dump().c_str());
4303 result.append("\n");
4304 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004305}
4306
Mathias Agopian13127d82013-03-05 17:47:11 -08004307const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004308SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004309 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004310 wp<IBinder> dpy;
4311 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4312 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4313 dpy = mDisplays.keyAt(i);
4314 break;
4315 }
4316 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004317 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004318 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4319 // Just use the primary display so we have something to return
4320 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4321 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004322 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004323}
4324
Keun young Park63f165f2012-08-31 10:53:36 -07004325bool SurfaceFlinger::startDdmConnection()
4326{
4327 void* libddmconnection_dso =
4328 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4329 if (!libddmconnection_dso) {
4330 return false;
4331 }
4332 void (*DdmConnection_start)(const char* name);
4333 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004334 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004335 if (!DdmConnection_start) {
4336 dlclose(libddmconnection_dso);
4337 return false;
4338 }
4339 (*DdmConnection_start)(getServiceName());
4340 return true;
4341}
4342
Chia-I Wu28f320b2018-05-03 11:02:56 -07004343void SurfaceFlinger::updateColorMatrixLocked() {
4344 mat4 colorMatrix;
4345 if (mGlobalSaturationFactor != 1.0f) {
4346 // Rec.709 luma coefficients
4347 float3 luminance{0.213f, 0.715f, 0.072f};
4348 luminance *= 1.0f - mGlobalSaturationFactor;
4349 mat4 saturationMatrix = mat4(
4350 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4351 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4352 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4353 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4354 );
4355 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4356 } else {
4357 colorMatrix = mClientColorMatrix * mDaltonizer();
4358 }
4359
4360 if (mCurrentState.colorMatrix != colorMatrix) {
4361 mCurrentState.colorMatrix = colorMatrix;
4362 mCurrentState.colorMatrixChanged = true;
4363 setTransactionFlags(eTransactionNeeded);
4364 }
4365}
4366
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004367status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004368 switch (code) {
4369 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004370 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004371 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004372 case CLEAR_ANIMATION_FRAME_STATS:
4373 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004374 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004375 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004376 case ENABLE_VSYNC_INJECTIONS:
4377 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004378 {
4379 // codes that require permission check
4380 IPCThreadState* ipc = IPCThreadState::self();
4381 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004382 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004383 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004384 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004385 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004386 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004387 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004388 break;
4389 }
Robert Carr1db73f62016-12-21 12:58:51 -08004390 /*
4391 * Calling setTransactionState is safe, because you need to have been
4392 * granted a reference to Client* and Handle* to do anything with it.
4393 *
4394 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4395 */
4396 case SET_TRANSACTION_STATE:
4397 case CREATE_SCOPED_CONNECTION:
4398 {
4399 return OK;
4400 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004401 case CAPTURE_SCREEN:
4402 {
4403 // codes that require permission check
4404 IPCThreadState* ipc = IPCThreadState::self();
4405 const int pid = ipc->getCallingPid();
4406 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004407 if ((uid != AID_GRAPHICS) &&
4408 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004409 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004410 return PERMISSION_DENIED;
4411 }
4412 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004413 }
chaviwa76b2712017-09-20 12:02:26 -07004414 case CAPTURE_LAYERS: {
4415 IPCThreadState* ipc = IPCThreadState::self();
4416 const int pid = ipc->getCallingPid();
4417 const int uid = ipc->getCallingUid();
4418 if ((uid != AID_GRAPHICS) &&
4419 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4420 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4421 return PERMISSION_DENIED;
4422 }
4423 break;
4424 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004425 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004426 return OK;
4427}
4428
4429status_t SurfaceFlinger::onTransact(
4430 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4431{
4432 status_t credentialCheck = CheckTransactCodeCredentials(code);
4433 if (credentialCheck != OK) {
4434 return credentialCheck;
4435 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004436
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004437 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4438 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004439 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004440 IPCThreadState* ipc = IPCThreadState::self();
4441 const int uid = ipc->getCallingUid();
4442 if (CC_UNLIKELY(uid != AID_SYSTEM
4443 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004444 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004445 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004446 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004447 return PERMISSION_DENIED;
4448 }
4449 int n;
4450 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004451 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004452 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004453 return NO_ERROR;
4454 case 1002: // SHOW_UPDATES
4455 n = data.readInt32();
4456 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004457 invalidateHwcGeometry();
4458 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004459 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004460 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004461 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004462 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004463 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004464 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004465 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004466 setTransactionFlags(
4467 eTransactionNeeded|
4468 eDisplayTransactionNeeded|
4469 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004470 return NO_ERROR;
4471 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004472 case 1006:{ // send empty update
4473 signalRefresh();
4474 return NO_ERROR;
4475 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004476 case 1008: // toggle use of hw composer
4477 n = data.readInt32();
4478 mDebugDisableHWC = n ? 1 : 0;
4479 invalidateHwcGeometry();
4480 repaintEverything();
4481 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004482 case 1009: // toggle use of transform hint
4483 n = data.readInt32();
4484 mDebugDisableTransformHint = n ? 1 : 0;
4485 invalidateHwcGeometry();
4486 repaintEverything();
4487 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004488 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004489 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004490 reply->writeInt32(0);
4491 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004492 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004493 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004494 return NO_ERROR;
4495 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004496 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004497 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004498 return NO_ERROR;
4499 }
4500 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004501 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004502 // daltonize
4503 n = data.readInt32();
4504 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004505 case 1:
4506 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4507 break;
4508 case 2:
4509 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4510 break;
4511 case 3:
4512 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4513 break;
4514 default:
4515 mDaltonizer.setType(ColorBlindnessType::None);
4516 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004517 }
4518 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004519 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004520 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004521 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004522 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004523
4524 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004525 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004526 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004527 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004528 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004529 // apply a color matrix
4530 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004531 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004532 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004533 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004534 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004535 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004536 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004537 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004538 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004539 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004540 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004541
4542 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4543 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004544 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004545 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4546 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4547 }
4548
Chia-I Wu28f320b2018-05-03 11:02:56 -07004549 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004550 return NO_ERROR;
4551 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004552 // This is an experimental interface
4553 // Needs to be shifted to proper binder interface when we productize
4554 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004555 n = data.readInt32();
4556 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004557 return NO_ERROR;
4558 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004559 case 1017: {
4560 n = data.readInt32();
4561 mForceFullDamage = static_cast<bool>(n);
4562 return NO_ERROR;
4563 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004564 case 1018: { // Modify Choreographer's phase offset
4565 n = data.readInt32();
4566 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4567 return NO_ERROR;
4568 }
4569 case 1019: { // Modify SurfaceFlinger's phase offset
4570 n = data.readInt32();
4571 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4572 return NO_ERROR;
4573 }
Irvel468051e2016-06-13 16:44:44 -07004574 case 1020: { // Layer updates interceptor
4575 n = data.readInt32();
4576 if (n) {
4577 ALOGV("Interceptor enabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004578 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004579 }
4580 else{
4581 ALOGV("Interceptor disabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004582 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004583 }
4584 return NO_ERROR;
4585 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004586 case 1021: { // Disable HWC virtual displays
4587 n = data.readInt32();
4588 mUseHwcVirtualDisplays = !n;
4589 return NO_ERROR;
4590 }
Romain Guy0147a172017-06-01 13:53:56 -07004591 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004592 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004593 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004594
Chia-I Wu28f320b2018-05-03 11:02:56 -07004595 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004596 return NO_ERROR;
4597 }
Romain Guy54f154a2017-10-24 21:40:32 +01004598 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004599 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004600 invalidateHwcGeometry();
4601 repaintEverything();
4602 return NO_ERROR;
4603 }
4604 case 1024: { // Is wide color gamut rendering/color management supported?
4605 reply->writeBool(hasWideColorDisplay);
4606 return NO_ERROR;
4607 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004608 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004609 n = data.readInt32();
4610 if (n) {
4611 ALOGV("LayerTracing enabled");
4612 mTracing.enable();
4613 doTracing("tracing.enable");
4614 reply->writeInt32(NO_ERROR);
4615 } else {
4616 ALOGV("LayerTracing disabled");
4617 status_t err = mTracing.disable();
4618 reply->writeInt32(err);
4619 }
4620 return NO_ERROR;
4621 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004622 case 1026: { // Get layer tracing status
4623 reply->writeBool(mTracing.isEnabled());
4624 return NO_ERROR;
4625 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004626 // Is a DisplayColorSetting supported?
4627 case 1027: {
Chia-I Wu0d711262018-05-21 15:19:35 -07004628 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
4629 if (!hw) {
4630 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004631 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004632
4633 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4634 switch (setting) {
4635 case DisplayColorSetting::MANAGED:
4636 reply->writeBool(hasWideColorDisplay);
4637 break;
4638 case DisplayColorSetting::UNMANAGED:
4639 reply->writeBool(true);
4640 break;
4641 case DisplayColorSetting::ENHANCED:
4642 reply->writeBool(hw->hasRenderIntent(RenderIntent::ENHANCE));
4643 break;
4644 default: // vendor display color setting
4645 reply->writeBool(hw->hasRenderIntent(static_cast<RenderIntent>(setting)));
4646 break;
4647 }
4648 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004649 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004650 }
4651 }
4652 return err;
4653}
4654
Steven Thomas6d8110b2017-08-31 18:24:21 -07004655void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004656 android_atomic_or(1, &mRepaintEverything);
4657 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004658}
4659
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004660// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4661class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004662public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004663 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4664 ~WindowDisconnector() {
4665 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004666 }
4667
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004668private:
4669 ANativeWindow* mWindow;
4670 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004671};
4672
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004673status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4674 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4675 int32_t minLayerZ, int32_t maxLayerZ,
4676 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004677 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004678 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004679
chaviwa76b2712017-09-20 12:02:26 -07004680 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4681
4682 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004683 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4684
chaviwa76b2712017-09-20 12:02:26 -07004685 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4686
4687 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4688 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004689 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004690}
4691
4692status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004693 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004694 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004695 ATRACE_CALL();
4696
4697 class LayerRenderArea : public RenderArea {
4698 public:
Robert Carr578038f2018-03-09 12:25:24 -08004699 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4700 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004701 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004702 mLayer(layer),
4703 mCrop(crop),
4704 mFlinger(flinger),
4705 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004706 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004707 Rect getBounds() const override {
4708 const Layer::State& layerState(mLayer->getDrawingState());
4709 return Rect(layerState.active.w, layerState.active.h);
4710 }
4711 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4712 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4713 bool isSecure() const override { return false; }
4714 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004715 Rect getSourceCrop() const override {
4716 if (mCrop.isEmpty()) {
4717 return getBounds();
4718 } else {
4719 return mCrop;
4720 }
4721 }
Robert Carr578038f2018-03-09 12:25:24 -08004722 class ReparentForDrawing {
4723 public:
4724 const sp<Layer>& oldParent;
4725 const sp<Layer>& newParent;
4726
4727 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4728 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004729 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004730 }
Robert Carr15eae092018-03-23 13:43:53 -07004731 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004732 };
4733
4734 void render(std::function<void()> drawLayers) override {
4735 if (!mChildrenOnly) {
4736 mTransform = mLayer->getTransform().inverse();
4737 drawLayers();
4738 } else {
4739 Rect bounds = getBounds();
4740 screenshotParentLayer =
4741 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4742 bounds.getWidth(), bounds.getHeight(), 0);
4743
4744 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4745 drawLayers();
4746 }
4747 }
chaviwa76b2712017-09-20 12:02:26 -07004748
chaviwa76b2712017-09-20 12:02:26 -07004749 private:
chaviw7206d492017-11-10 16:16:12 -08004750 const sp<Layer> mLayer;
4751 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004752
4753 // In the "childrenOnly" case we reparent the children to a screenshot
4754 // layer which has no properties set and which does not draw.
4755 sp<ContainerLayer> screenshotParentLayer;
4756 Transform mTransform;
4757
4758 SurfaceFlinger* mFlinger;
4759 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004760 };
4761
4762 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4763 auto parent = layerHandle->owner.promote();
4764
chaviw7206d492017-11-10 16:16:12 -08004765 if (parent == nullptr || parent->isPendingRemoval()) {
4766 ALOGE("captureLayers called with a removed parent");
4767 return NAME_NOT_FOUND;
4768 }
4769
Robert Carr578038f2018-03-09 12:25:24 -08004770 const int uid = IPCThreadState::self()->getCallingUid();
4771 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4772 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4773 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4774 return PERMISSION_DENIED;
4775 }
4776
chaviw7206d492017-11-10 16:16:12 -08004777 Rect crop(sourceCrop);
4778 if (sourceCrop.width() <= 0) {
4779 crop.left = 0;
4780 crop.right = parent->getCurrentState().active.w;
4781 }
4782
4783 if (sourceCrop.height() <= 0) {
4784 crop.top = 0;
4785 crop.bottom = parent->getCurrentState().active.h;
4786 }
4787
4788 int32_t reqWidth = crop.width() * frameScale;
4789 int32_t reqHeight = crop.height() * frameScale;
4790
Robert Carr578038f2018-03-09 12:25:24 -08004791 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004792
Robert Carr578038f2018-03-09 12:25:24 -08004793 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004794 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4795 if (!layer->isVisible()) {
4796 return;
Robert Carr578038f2018-03-09 12:25:24 -08004797 } else if (childrenOnly && layer == parent.get()) {
4798 return;
chaviwa76b2712017-09-20 12:02:26 -07004799 }
4800 visitor(layer);
4801 });
4802 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004803 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004804}
4805
4806status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4807 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004808 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004809 bool useIdentityTransform) {
4810 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004811
chaviwa76b2712017-09-20 12:02:26 -07004812 renderArea.updateDimensions();
4813
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004814 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4815 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4816 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4817 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004818
4819 // This mutex protects syncFd and captureResult for communication of the return values from the
4820 // main thread back to this Binder thread
4821 std::mutex captureMutex;
4822 std::condition_variable captureCondition;
4823 std::unique_lock<std::mutex> captureLock(captureMutex);
4824 int syncFd = -1;
4825 std::optional<status_t> captureResult;
4826
Robert Carr03480e22018-01-04 16:02:06 -08004827 const int uid = IPCThreadState::self()->getCallingUid();
4828 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4829
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004830 sp<LambdaMessage> message = new LambdaMessage([&]() {
4831 // If there is a refresh pending, bug out early and tell the binder thread to try again
4832 // after the refresh.
4833 if (mRefreshPending) {
4834 ATRACE_NAME("Skipping screenshot for now");
4835 std::unique_lock<std::mutex> captureLock(captureMutex);
4836 captureResult = std::make_optional<status_t>(EAGAIN);
4837 captureCondition.notify_one();
4838 return;
4839 }
4840
4841 status_t result = NO_ERROR;
4842 int fd = -1;
4843 {
4844 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004845 renderArea.render([&]() {
4846 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4847 useIdentityTransform, forSystem, &fd);
4848 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004849 }
4850
4851 {
4852 std::unique_lock<std::mutex> captureLock(captureMutex);
4853 syncFd = fd;
4854 captureResult = std::make_optional<status_t>(result);
4855 captureCondition.notify_one();
4856 }
4857 });
4858
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004859 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004860 if (result == NO_ERROR) {
4861 captureCondition.wait(captureLock, [&]() { return captureResult; });
4862 while (*captureResult == EAGAIN) {
4863 captureResult.reset();
4864 result = postMessageAsync(message);
4865 if (result != NO_ERROR) {
4866 return result;
4867 }
4868 captureCondition.wait(captureLock, [&]() { return captureResult; });
4869 }
4870 result = *captureResult;
4871 }
4872
4873 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004874 sync_wait(syncFd, -1);
4875 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004876 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004877
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004878 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004879}
4880
chaviwa76b2712017-09-20 12:02:26 -07004881void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4882 TraverseLayersFunction traverseLayers, bool yswap,
4883 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004884 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004885
Lloyd Pique144e1162017-12-20 16:44:52 -08004886 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004887
4888 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004889 const auto raWidth = renderArea.getWidth();
4890 const auto raHeight = renderArea.getHeight();
4891
4892 const auto reqWidth = renderArea.getReqWidth();
4893 const auto reqHeight = renderArea.getReqHeight();
4894 Rect sourceCrop = renderArea.getSourceCrop();
4895
4896 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4897 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004898
Dan Stozac1879002014-05-22 15:59:05 -07004899 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004900 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004901 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004902 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004903 }
4904
4905 // ensure that sourceCrop is inside screen
4906 if (sourceCrop.left < 0) {
4907 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4908 }
chaviwa76b2712017-09-20 12:02:26 -07004909 if (sourceCrop.right > raWidth) {
4910 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004911 }
4912 if (sourceCrop.top < 0) {
4913 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4914 }
chaviwa76b2712017-09-20 12:02:26 -07004915 if (sourceCrop.bottom > raHeight) {
4916 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004917 }
4918
Chia-I Wu36574d92018-05-16 10:54:36 -07004919 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
4920 engine.setOutputDataSpace(Dataspace::SRGB);
4921 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07004922
Mathias Agopian180f10d2013-04-10 22:55:41 -07004923 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004924 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004925
4926 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004927 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4928 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004929 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004930
chaviw50da5042018-04-09 13:49:37 -07004931 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004932 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07004933 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004934
chaviwa76b2712017-09-20 12:02:26 -07004935 traverseLayers([&](Layer* layer) {
4936 if (filtering) layer->setFiltering(true);
4937 layer->draw(renderArea, useIdentityTransform);
4938 if (filtering) layer->setFiltering(false);
4939 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004940}
4941
chaviwa76b2712017-09-20 12:02:26 -07004942status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4943 TraverseLayersFunction traverseLayers,
4944 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004945 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08004946 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07004947 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004948 ATRACE_CALL();
4949
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004950 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004951
4952 traverseLayers([&](Layer* layer) {
4953 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4954 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004955
Robert Carr03480e22018-01-04 16:02:06 -08004956 // We allow the system server to take screenshots of secure layers for
4957 // use in situations like the Screen-rotation animation and place
4958 // the impetus on WindowManager to not persist them.
4959 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004960 ALOGW("FB is protected: PERMISSION_DENIED");
4961 return PERMISSION_DENIED;
4962 }
4963
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004964 // this binds the given EGLImage as a framebuffer for the
4965 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08004966 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08004967 if (bufferBond.getStatus() != NO_ERROR) {
4968 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004969 return INVALID_OPERATION;
4970 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004971
Dan Stozaabcda352017-06-01 14:37:39 -07004972 // this will in fact render into our dequeued buffer
4973 // via an FBO, which means we didn't have to create
4974 // an EGLSurface and therefore we're not
4975 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004976 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004977
Dan Stozaabcda352017-06-01 14:37:39 -07004978 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08004979 getRenderEngine().finish();
4980 *outSyncFd = -1;
4981
chaviwa76b2712017-09-20 12:02:26 -07004982 const auto reqWidth = renderArea.getReqWidth();
4983 const auto reqHeight = renderArea.getReqHeight();
4984
Dan Stozaabcda352017-06-01 14:37:39 -07004985 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4986 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004987 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004988 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08004989 } else {
4990 base::unique_fd syncFd = getRenderEngine().flush();
4991 if (syncFd < 0) {
4992 getRenderEngine().finish();
4993 }
4994 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07004995 }
4996
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004997 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004998}
4999
Mathias Agopiand5556842013-09-19 17:08:37 -07005000void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005001 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005002 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005003 for (size_t y = 0; y < h; y++) {
5004 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5005 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005006 if (p[x] != 0xFF000000) return;
5007 }
5008 }
chaviwa76b2712017-09-20 12:02:26 -07005009 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005010
Robert Carr2047fae2016-11-28 14:09:09 -08005011 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005012 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005013 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005014 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5015 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5016 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5017 static_cast<float>(state.color.a));
5018 i++;
5019 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005020 }
5021}
5022
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005023// ---------------------------------------------------------------------------
5024
Dan Stoza412903f2017-04-27 13:42:17 -07005025void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5026 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005027}
5028
Dan Stoza412903f2017-04-27 13:42:17 -07005029void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5030 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005031}
5032
chaviwa76b2712017-09-20 12:02:26 -07005033void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
5034 int32_t maxLayerZ,
5035 const LayerVector::Visitor& visitor) {
5036 // We loop through the first level of layers without traversing,
5037 // as we need to interpret min/max layer Z in the top level Z space.
5038 for (const auto& layer : mDrawingState.layersSortedByZ) {
5039 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5040 continue;
5041 }
5042 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005043 // relative layers are traversed in Layer::traverseInZOrder
5044 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005045 continue;
5046 }
5047 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005048 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5049 return;
5050 }
chaviwa76b2712017-09-20 12:02:26 -07005051 if (!layer->isVisible()) {
5052 return;
5053 }
5054 visitor(layer);
5055 });
5056 }
5057}
5058
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005059}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005060
5061
5062#if defined(__gl_h_)
5063#error "don't include gl/gl.h in this file"
5064#endif
5065
5066#if defined(__gl2_h_)
5067#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005068#endif