blob: da6447624c28d1f49070db1909ed543906257711 [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 -0800161DisplayColorSetting toDisplayColorSetting(int value) {
162 switch(value) {
163 case 0:
164 return DisplayColorSetting::MANAGED;
165 case 1:
166 return DisplayColorSetting::UNMANAGED;
167 case 2:
168 return DisplayColorSetting::ENHANCED;
169 default:
170 return DisplayColorSetting::MANAGED;
171 }
172}
173
174std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
175 switch(displayColorSetting) {
176 case DisplayColorSetting::MANAGED:
177 return std::string("Natural Mode");
178 case DisplayColorSetting::UNMANAGED:
179 return std::string("Saturated Mode");
180 case DisplayColorSetting::ENHANCED:
181 return std::string("Auto Color Mode");
182 }
183 return std::string("Unknown Display Color Setting");
184}
185
Lloyd Pique09594832018-01-22 17:48:03 -0800186NativeWindowSurface::~NativeWindowSurface() = default;
187
188namespace impl {
189
190class NativeWindowSurface final : public android::NativeWindowSurface {
191public:
192 static std::unique_ptr<android::NativeWindowSurface> create(
193 const sp<IGraphicBufferProducer>& producer) {
194 return std::make_unique<NativeWindowSurface>(producer);
195 }
196
197 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
198 : surface(new Surface(producer, false)) {}
199
200 ~NativeWindowSurface() override = default;
201
202private:
203 sp<ANativeWindow> getNativeWindow() const override { return surface; }
204
205 void preallocateBuffers() override { surface->allocateBuffers(); }
206
207 sp<Surface> surface;
208};
209
210} // namespace impl
211
David Sodmanbc815282017-11-05 18:57:52 -0800212SurfaceFlingerBE::SurfaceFlingerBE()
213 : mHwcServiceName(getHwcServiceName()),
214 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800215 mFrameBuckets(),
216 mTotalTime(0),
217 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800218 mComposerSequenceId(0) {
219}
220
Lloyd Pique2d3ee6d2018-01-17 13:42:24 -0800221SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800222 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800223 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700224 mTransactionPending(false),
225 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700226 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700227 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700228 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800229 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800230 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800231 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800232 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800233 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800234 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700235 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700236 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700237 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700238 mDebugInSwapBuffers(0),
239 mLastSwapBufferTime(0),
240 mDebugInTransaction(0),
241 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700242 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700243 mForceFullDamage(false),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000244 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700245 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700246 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800247 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800248 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700249 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800250 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique09594832018-01-22 17:48:03 -0800251 mCreateBufferQueue(&BufferQueue::createBufferQueue),
252 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Pique2d3ee6d2018-01-17 13:42:24 -0800253
254SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800255 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800256
257 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
258 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
259
260 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
261 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
262
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800263 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
264 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800265
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700266 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
267 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
268
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700269 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
270 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
271
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800272 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
273 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
274
Steven Thomas050b2c82017-03-06 11:45:16 -0800275 // Vr flinger is only enabled on Daydream ready devices.
276 useVrFlinger = getBool< ISurfaceFlingerConfigs,
277 &ISurfaceFlingerConfigs::useVrFlinger>(false);
278
Fabien Sanglard1971b632017-03-10 14:50:03 -0800279 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
280 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
281
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600282 hasWideColorDisplay =
283 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
284
David Sodman99974d22017-11-28 12:04:33 -0800285 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700286
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800287 // debugging stuff...
288 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700289
Mathias Agopianb4b17302013-03-20 18:36:41 -0700290 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700291 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700292
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800293 property_get("debug.sf.showupdates", value, "0");
294 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700295
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700296 property_get("debug.sf.ddms", value, "0");
297 mDebugDDMS = atoi(value);
298 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700299 if (!startDdmConnection()) {
300 // start failed, and DDMS debugging not enabled
301 mDebugDDMS = 0;
302 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700303 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700304 ALOGI_IF(mDebugRegion, "showupdates enabled");
305 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700306
307 property_get("debug.sf.disable_backpressure", value, "0");
308 mPropagateBackpressure = !atoi(value);
309 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700310
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800311 property_get("debug.sf.enable_hwc_vds", value, "0");
312 mUseHwcVirtualDisplays = atoi(value);
313 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800314
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800315 property_get("ro.sf.disable_triple_buffer", value, "1");
316 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800317 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700318
Dan Stoza0a0158c2018-03-16 13:38:54 -0700319 // TODO (b/74616334): Reduce the default value once we isolate the leak
320 const size_t defaultListSize = 4 * MAX_LAYERS;
321 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
322 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
323
Dan Stoza2713c302018-03-28 17:07:36 -0700324 property_get("debug.sf.early_phase_offset_ns", value, "0");
325 const int earlyWakeupOffsetOffsetNs = atoi(value);
326 ALOGI_IF(earlyWakeupOffsetOffsetNs != 0, "Enabling separate early offset");
327 mVsyncModulator.setPhaseOffsets(sfVsyncPhaseOffsetNs - earlyWakeupOffsetOffsetNs,
328 sfVsyncPhaseOffsetNs);
329
Romain Guy11d63f42017-07-20 12:47:14 -0700330 // We should be reading 'persist.sys.sf.color_saturation' here
331 // but since /data may be encrypted, we need to wait until after vold
332 // comes online to attempt to read the property. The property is
333 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800334
335 if (useTrebleTestingOverride()) {
336 // Without the override SurfaceFlinger cannot connect to HIDL
337 // services that are not listed in the manifests. Considered
338 // deriving the setting from the set service name, but it
339 // would be brittle if the name that's not 'default' is used
340 // for production purposes later on.
341 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
342 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800343}
344
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800345void SurfaceFlinger::onFirstRef()
346{
Lloyd Pique9123ae52018-01-22 17:14:00 -0800347 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800348}
349
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800350SurfaceFlinger::~SurfaceFlinger()
351{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800352}
353
Dan Stozac7014012014-02-14 15:03:43 -0800354void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800355{
356 // the window manager died on us. prepare its eulogy.
357
Andy McFadden13a082e2012-08-24 10:16:42 -0700358 // restore initial conditions (default device unblank, etc)
359 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800360
361 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700362 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800363}
364
Robert Carr1db73f62016-12-21 12:58:51 -0800365static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700366 status_t err = client->initCheck();
367 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800368 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800369 }
Robert Carr1db73f62016-12-21 12:58:51 -0800370 return nullptr;
371}
372
373sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
374 return initClient(new Client(this));
375}
376
377sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
378 const sp<IGraphicBufferProducer>& gbp) {
379 if (authenticateSurfaceTexture(gbp) == false) {
380 return nullptr;
381 }
382 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
383 if (layer == nullptr) {
384 return nullptr;
385 }
386
387 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800388}
389
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700390sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
391 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700392{
393 class DisplayToken : public BBinder {
394 sp<SurfaceFlinger> flinger;
395 virtual ~DisplayToken() {
396 // no more references, this display must be terminated
397 Mutex::Autolock _l(flinger->mStateLock);
398 flinger->mCurrentState.displays.removeItem(this);
399 flinger->setTransactionFlags(eDisplayTransactionNeeded);
400 }
401 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700402 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700403 : flinger(flinger) {
404 }
405 };
406
407 sp<BBinder> token = new DisplayToken(this);
408
409 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700410 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700411 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700412 mCurrentState.displays.add(token, info);
Lloyd Pique4d234852018-01-22 17:21:36 -0800413 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700414 return token;
415}
416
Jesse Hall6c913be2013-08-08 12:15:49 -0700417void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
418 Mutex::Autolock _l(mStateLock);
419
420 ssize_t idx = mCurrentState.displays.indexOfKey(display);
421 if (idx < 0) {
422 ALOGW("destroyDisplay: invalid display token");
423 return;
424 }
425
426 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
427 if (!info.isVirtualDisplay()) {
428 ALOGE("destroyDisplay called for non-virtual display");
429 return;
430 }
Lloyd Pique4d234852018-01-22 17:21:36 -0800431 mInterceptor->saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700432 mCurrentState.displays.removeItemsAt(idx);
433 setTransactionFlags(eDisplayTransactionNeeded);
434}
435
Mathias Agopiane57f2922012-08-09 16:29:12 -0700436sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700437 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700438 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800439 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700440 }
Jesse Hall692c7232012-11-08 15:41:56 -0800441 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700442}
443
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800444void SurfaceFlinger::bootFinished()
445{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700446 if (mStartPropertySetThread->join() != NO_ERROR) {
447 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800448 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800449 const nsecs_t now = systemTime();
450 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000451 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700452
453 // wait patiently for the window manager death
454 const String16 name("window");
455 sp<IBinder> window(defaultServiceManager()->getService(name));
456 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700457 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700458 }
459
Steven Thomas050b2c82017-03-06 11:45:16 -0800460 if (mVrFlinger) {
461 mVrFlinger->OnBootFinished();
462 }
463
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700464 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700465 // formerly we would just kill the process, but we now ask it to exit so it
466 // can choose where to stop the animation.
467 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700468
469 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
470 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
471 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700472
Thierry Strudel2924d012017-08-14 15:19:37 -0700473 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700474 readPersistentProperties();
475 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700476 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800477}
478
Mathias Agopian3f844832013-08-07 21:24:32 -0700479void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700480 class MessageDestroyGLTexture : public MessageBase {
Lloyd Pique144e1162017-12-20 16:44:52 -0800481 RE::RenderEngine& engine;
Mathias Agopian3f844832013-08-07 21:24:32 -0700482 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700483 public:
Lloyd Pique144e1162017-12-20 16:44:52 -0800484 MessageDestroyGLTexture(RE::RenderEngine& engine, uint32_t texture)
485 : engine(engine), texture(texture) {}
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700486 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700487 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700488 return true;
489 }
490 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700491 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700492}
493
Lloyd Piquee83f9312018-02-01 12:53:17 -0800494class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700495public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700496 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000497 const char* name) :
498 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700499 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700500 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000501 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
502 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700503 mDispSync(dispSync),
504 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700505 mVsyncMutex(),
506 mPhaseOffset(phaseOffset),
507 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700508
Lloyd Piquee83f9312018-02-01 12:53:17 -0800509 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700510
Lloyd Piquee83f9312018-02-01 12:53:17 -0800511 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700512 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700513 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000514 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700515 static_cast<DispSync::Callback*>(this));
516 if (err != NO_ERROR) {
517 ALOGE("error registering vsync callback: %s (%d)",
518 strerror(-err), err);
519 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700520 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700521 } else {
522 status_t err = mDispSync->removeEventListener(
523 static_cast<DispSync::Callback*>(this));
524 if (err != NO_ERROR) {
525 ALOGE("error unregistering vsync callback: %s (%d)",
526 strerror(-err), err);
527 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700528 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700529 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700530 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700531 }
532
Lloyd Piquee83f9312018-02-01 12:53:17 -0800533 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700534 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700535 mCallback = callback;
536 }
537
Lloyd Piquee83f9312018-02-01 12:53:17 -0800538 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700539 Mutex::Autolock lock(mVsyncMutex);
540
541 // Normalize phaseOffset to [0, period)
542 auto period = mDispSync->getPeriod();
543 phaseOffset %= period;
544 if (phaseOffset < 0) {
545 // If we're here, then phaseOffset is in (-period, 0). After this
546 // operation, it will be in (0, period)
547 phaseOffset += period;
548 }
549 mPhaseOffset = phaseOffset;
550
551 // If we're not enabled, we don't need to mess with the listeners
552 if (!mEnabled) {
553 return;
554 }
555
Dan Stoza2713c302018-03-28 17:07:36 -0700556 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
557 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700558 if (err != NO_ERROR) {
Dan Stoza2713c302018-03-28 17:07:36 -0700559 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700560 strerror(-err), err);
561 }
562 }
563
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700564private:
565 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800566 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700567 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700568 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700569 callback = mCallback;
570
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700571 if (mTraceVsync) {
572 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700573 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700574 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700575 }
576
Peiyong Lin566a3b42018-01-09 18:22:43 -0800577 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700578 callback->onVSyncEvent(when);
579 }
580 }
581
Tim Murray4a4e4a22016-04-19 16:29:23 +0000582 const char* const mName;
583
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700584 int mValue;
585
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700586 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700587 const String8 mVsyncOnLabel;
588 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700589
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700590 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700591
592 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800593 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700594
595 Mutex mVsyncMutex; // Protects the following
596 nsecs_t mPhaseOffset;
597 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700598};
599
Lloyd Piquee83f9312018-02-01 12:53:17 -0800600class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700601public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800602 InjectVSyncSource() = default;
603 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700604
Lloyd Piquee83f9312018-02-01 12:53:17 -0800605 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700606 std::lock_guard<std::mutex> lock(mCallbackMutex);
607 mCallback = callback;
608 }
609
Lloyd Piquee83f9312018-02-01 12:53:17 -0800610 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700611 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700612 if (mCallback) {
613 mCallback->onVSyncEvent(when);
614 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700615 }
616
Lloyd Piquee83f9312018-02-01 12:53:17 -0800617 void setVSyncEnabled(bool) override {}
618 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700619
620private:
621 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800622 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700623};
624
Wei Wangf9b05ee2017-07-19 20:59:39 -0700625// Do not call property_set on main thread which will be blocked by init
626// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700627void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700628 ALOGI( "SurfaceFlinger's main thread ready to run. "
629 "Initializing graphics H/W...");
630
Thierry Strudel2924d012017-08-14 15:19:37 -0700631 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900632
Steven Thomasb02664d2017-07-26 18:48:28 -0700633 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800634
Steven Thomasb02664d2017-07-26 18:48:28 -0700635 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800636 mEventThreadSource =
637 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
638 true, "app");
639 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(), *this, false,
640 "appEventThread");
641 mSfEventThreadSource =
642 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
643 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800644
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800645 mSFEventThread = std::make_unique<impl::EventThread>(mSfEventThreadSource.get(), *this, true,
646 "sfEventThread");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800647 mEventQueue->setEventThread(mSFEventThread.get());
Dan Stoza2713c302018-03-28 17:07:36 -0700648 mVsyncModulator.setEventThread(mSFEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800649
Steven Thomasb02664d2017-07-26 18:48:28 -0700650 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800651 getBE().mRenderEngine =
652 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
653 hasWideColorDisplay
654 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
655 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800656 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700657
658 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
659 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800660 getBE().mHwc.reset(
661 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700662 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800663 // Process any initial hotplug and resulting display changes.
664 processDisplayHotplugEventsLocked();
665 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
666 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800667
Lloyd Piquefcd86612017-12-14 17:15:36 -0800668 // make the default display GLContext current so that we can create textures
669 // when creating Layers (which may happens before we render something)
670 getDefaultDisplayDeviceLocked()->makeCurrent();
671
Steven Thomas050b2c82017-03-06 11:45:16 -0800672 if (useVrFlinger) {
673 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700674 // This callback is called from the vr flinger dispatch thread. We
675 // need to call signalTransaction(), which requires holding
676 // mStateLock when we're not on the main thread. Acquiring
677 // mStateLock from the vr flinger dispatch thread might trigger a
678 // deadlock in surface flinger (see b/66916578), so post a message
679 // to be handled on the main thread instead.
680 sp<LambdaMessage> message = new LambdaMessage([=]() {
681 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
682 mVrFlingerRequestsDisplay = requestDisplay;
683 signalTransaction();
684 });
685 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800686 };
David Sodman105b7dc2017-11-04 20:28:14 -0700687 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
688 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800689 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800690 if (!mVrFlinger) {
691 ALOGE("Failed to start vrflinger");
692 }
693 }
694
Lloyd Pique0c3a8832018-01-22 17:31:47 -0800695 mEventControlThread = std::make_unique<impl::EventControlThread>(
696 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700697
Mathias Agopian92a979a2012-08-02 18:32:23 -0700698 // initialize our drawing state
699 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700700
Andy McFadden13a082e2012-08-24 10:16:42 -0700701 // set initial conditions (e.g. unblank default device)
702 initializeDisplays();
703
David Sodmanbc815282017-11-05 18:57:52 -0800704 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700705
Wei Wangf9b05ee2017-07-19 20:59:39 -0700706 // Inform native graphics APIs whether the present timestamp is supported:
707 if (getHwComposer().hasCapability(
708 HWC2::Capability::PresentFenceIsNotReliable)) {
709 mStartPropertySetThread = new StartPropertySetThread(false);
710 } else {
711 mStartPropertySetThread = new StartPropertySetThread(true);
712 }
713
714 if (mStartPropertySetThread->Start() != NO_ERROR) {
715 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800716 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800717
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800718 mLegacySrgbSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(HWC_DISPLAY_PRIMARY,
719 Dataspace::SRGB_LINEAR);
720
Dan Stoza9e56aa02015-11-02 13:00:03 -0800721 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700722}
723
Romain Guy11d63f42017-07-20 12:47:14 -0700724void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700725 Mutex::Autolock _l(mStateLock);
726
Romain Guy11d63f42017-07-20 12:47:14 -0700727 char value[PROPERTY_VALUE_MAX];
728
729 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800730 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700731 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800732 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100733
734 property_get("persist.sys.sf.native_mode", value, "0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800735 mDisplayColorSetting = toDisplayColorSetting(atoi(value));
736 ALOGV("Display Color Setting is set to %s.",
737 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Romain Guy11d63f42017-07-20 12:47:14 -0700738}
739
Mathias Agopiana67e4182012-06-19 17:26:12 -0700740void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800741 // Start boot animation service by setting a property mailbox
742 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700743 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800744 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700745 if (mStartPropertySetThread->join() != NO_ERROR) {
746 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800747 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700748}
749
Mathias Agopian875d8e12013-06-07 15:35:48 -0700750size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800751 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700752}
753
Mathias Agopian875d8e12013-06-07 15:35:48 -0700754size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800755 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700756}
757
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800758// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800759
Jamie Gennis582270d2011-08-17 18:19:00 -0700760bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800761 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800762 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800763 return authenticateSurfaceTextureLocked(bufferProducer);
764}
765
766bool SurfaceFlinger::authenticateSurfaceTextureLocked(
767 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800768 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800769 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800770}
771
Brian Anderson6b376712017-04-04 10:51:39 -0700772status_t SurfaceFlinger::getSupportedFrameTimestamps(
773 std::vector<FrameEvent>* outSupported) const {
774 *outSupported = {
775 FrameEvent::REQUESTED_PRESENT,
776 FrameEvent::ACQUIRE,
777 FrameEvent::LATCH,
778 FrameEvent::FIRST_REFRESH_START,
779 FrameEvent::LAST_REFRESH_START,
780 FrameEvent::GPU_COMPOSITION_DONE,
781 FrameEvent::DEQUEUE_READY,
782 FrameEvent::RELEASE,
783 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700784 ConditionalLock _l(mStateLock,
785 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700786 if (!getHwComposer().hasCapability(
787 HWC2::Capability::PresentFenceIsNotReliable)) {
788 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
789 }
790 return NO_ERROR;
791}
792
Dan Stoza7f7da322014-05-02 15:26:25 -0700793status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
794 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800795 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700796 return BAD_VALUE;
797 }
798
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500799 if (!display.get())
800 return NAME_NOT_FOUND;
801
Jesse Hall692c7232012-11-08 15:41:56 -0800802 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700803 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800804 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700805 type = i;
806 break;
807 }
808 }
809
810 if (type < 0) {
811 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700812 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700813
Mathias Agopian8b736f12012-08-13 17:54:26 -0700814 // TODO: Not sure if display density should handled by SF any longer
815 class Density {
816 static int getDensityFromProperty(char const* propName) {
817 char property[PROPERTY_VALUE_MAX];
818 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800819 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700820 density = atoi(property);
821 }
822 return density;
823 }
824 public:
825 static int getEmuDensity() {
826 return getDensityFromProperty("qemu.sf.lcd_density"); }
827 static int getBuildDensity() {
828 return getDensityFromProperty("ro.sf.lcd_density"); }
829 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700830
Dan Stoza7f7da322014-05-02 15:26:25 -0700831 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700832
Steven Thomas6d8110b2017-08-31 18:24:21 -0700833 ConditionalLock _l(mStateLock,
834 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800835 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700836 DisplayInfo info = DisplayInfo();
837
Dan Stoza9e56aa02015-11-02 13:00:03 -0800838 float xdpi = hwConfig->getDpiX();
839 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700840
841 if (type == DisplayDevice::DISPLAY_PRIMARY) {
842 // The density of the device is provided by a build property
843 float density = Density::getBuildDensity() / 160.0f;
844 if (density == 0) {
845 // the build doesn't provide a density -- this is wrong!
846 // use xdpi instead
847 ALOGE("ro.sf.lcd_density must be defined as a build property");
848 density = xdpi / 160.0f;
849 }
850 if (Density::getEmuDensity()) {
851 // if "qemu.sf.lcd_density" is specified, it overrides everything
852 xdpi = ydpi = density = Density::getEmuDensity();
853 density /= 160.0f;
854 }
855 info.density = density;
856
857 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700858 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800859 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700860 } else {
861 // TODO: where should this value come from?
862 static const int TV_DENSITY = 213;
863 info.density = TV_DENSITY / 160.0f;
864 info.orientation = 0;
865 }
866
Dan Stoza9e56aa02015-11-02 13:00:03 -0800867 info.w = hwConfig->getWidth();
868 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700869 info.xdpi = xdpi;
870 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800871 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900872 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800873
Andy McFadden91b2ca82014-06-13 14:04:23 -0700874 // This is how far in advance a buffer must be queued for
875 // presentation at a given time. If you want a buffer to appear
876 // on the screen at time N, you must submit the buffer before
877 // (N - presentationDeadline).
878 //
879 // Normally it's one full refresh period (to give SF a chance to
880 // latch the buffer), but this can be reduced by configuring a
881 // DispSync offset. Any additional delays introduced by the hardware
882 // composer or panel must be accounted for here.
883 //
884 // We add an additional 1ms to allow for processing time and
885 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800886 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800887 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700888
889 // All non-virtual displays are currently considered secure.
890 info.secure = true;
891
Michael Wright28f24d02016-07-12 13:30:53 -0700892 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700893 }
894
Dan Stoza7f7da322014-05-02 15:26:25 -0700895 return NO_ERROR;
896}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700897
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800898status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700899 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800900 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700901 return BAD_VALUE;
902 }
903
904 // FIXME for now we always return stats for the primary display
905 memset(stats, 0, sizeof(*stats));
906 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
907 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
908 return NO_ERROR;
909}
910
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700911int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800912 if (display == nullptr) {
913 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800914 return BAD_VALUE;
915 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700916
917 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800918 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700919 return device->getActiveConfig();
920 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700921
Dan Stoza24a42e92015-03-09 10:04:11 -0700922 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700923}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700924
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700925void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
926 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
927 this);
928 int32_t type = hw->getDisplayType();
929 int currentMode = hw->getActiveConfig();
930
931 if (mode == currentMode) {
932 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
933 return;
934 }
935
936 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
937 ALOGW("Trying to set config for virtual display");
938 return;
939 }
940
941 hw->setActiveConfig(mode);
942 getHwComposer().setActiveConfig(type, mode);
943}
944
945status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
946 class MessageSetActiveConfig: public MessageBase {
947 SurfaceFlinger& mFlinger;
948 sp<IBinder> mDisplay;
949 int mMode;
950 public:
951 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
952 int mode) :
953 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
954 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700955 Vector<DisplayInfo> configs;
956 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700957 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700958 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700959 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700960 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700961 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700962 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800963 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700964 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700965 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700966 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
967 ALOGW("Attempt to set active config = %d for virtual display",
968 mMode);
969 } else {
970 mFlinger.setActiveConfigInternal(hw, mMode);
971 }
972 return true;
973 }
974 };
975 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
976 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700977 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700978}
Michael Wright28f24d02016-07-12 13:30:53 -0700979status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -0700980 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700981 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
982 return BAD_VALUE;
983 }
984
985 if (!display.get()) {
986 return NAME_NOT_FOUND;
987 }
988
989 int32_t type = NAME_NOT_FOUND;
990 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
991 if (display == mBuiltinDisplays[i]) {
992 type = i;
993 break;
994 }
995 }
996
997 if (type < 0) {
998 return type;
999 }
1000
Peiyong Lina52f0292018-03-14 17:26:31 -07001001 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001002 {
1003 ConditionalLock _l(mStateLock,
1004 std::this_thread::get_id() != mMainThreadId);
1005 modes = getHwComposer().getColorModes(type);
1006 }
Michael Wright28f24d02016-07-12 13:30:53 -07001007 outColorModes->clear();
1008 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1009
1010 return NO_ERROR;
1011}
1012
Peiyong Lina52f0292018-03-14 17:26:31 -07001013ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001014 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -07001015 if (device != nullptr) {
1016 return device->getActiveColorMode();
1017 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001018 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001019}
1020
1021void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001022 ColorMode mode, Dataspace dataSpace) {
Michael Wright28f24d02016-07-12 13:30:53 -07001023 int32_t type = hw->getDisplayType();
Peiyong Lina52f0292018-03-14 17:26:31 -07001024 ColorMode currentMode = hw->getActiveColorMode();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001025 Dataspace currentDataSpace = hw->getCompositionDataSpace();
Peiyong Lin38e9a562018-04-10 16:24:20 -07001026 RenderIntent currentRenderIntent = hw->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001027
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001028 // Natural Mode means it's color managed and the color must be right,
1029 // thus we pick RenderIntent::COLORIMETRIC as render intent.
1030 // Native Mode means the display is not color managed, and whichever
1031 // render intent is picked doesn't matter, thus return
1032 // RenderIntent::COLORIMETRIC as default here.
1033 RenderIntent renderIntent = RenderIntent::COLORIMETRIC;
1034
1035 // In Auto Color Mode, we want to strech to panel color space, right now
1036 // only the built-in display supports it.
1037 if (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
1038 mBuiltinDisplaySupportsEnhance &&
1039 hw->getDisplayType() == DisplayDevice::DISPLAY_PRIMARY) {
1040 renderIntent = RenderIntent::ENHANCE;
1041 }
Peiyong Lin38e9a562018-04-10 16:24:20 -07001042
1043 if (mode == currentMode && dataSpace == currentDataSpace &&
1044 renderIntent == currentRenderIntent) {
1045 return;
1046 }
1047
1048 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1049 ALOGW("Trying to set config for virtual display");
1050 return;
1051 }
1052
1053 hw->setActiveColorMode(mode);
1054 hw->setCompositionDataSpace(dataSpace);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001055 hw->setActiveRenderIntent(renderIntent);
1056 getHwComposer().setActiveColorMode(type, mode, renderIntent);
1057
1058 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
1059 decodeColorMode(mode).c_str(), mode,
1060 decodeRenderIntent(renderIntent).c_str(), renderIntent,
1061 hw->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001062}
1063
1064
1065status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001066 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -07001067 class MessageSetActiveColorMode: public MessageBase {
1068 SurfaceFlinger& mFlinger;
1069 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -07001070 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001071 public:
1072 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -07001073 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -07001074 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1075 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -07001076 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001077 mFlinger.getDisplayColorModes(mDisplay, &modes);
1078 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -07001079 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001080 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1081 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001082 return true;
1083 }
1084 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1085 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001086 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1087 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001088 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001089 ALOGW("Attempt to set active color mode %s %d for virtual display",
1090 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001091 } else {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001092 mFlinger.setActiveColorModeInternal(hw, mMode, Dataspace::UNKNOWN);
Michael Wright28f24d02016-07-12 13:30:53 -07001093 }
1094 return true;
1095 }
1096 };
1097 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1098 postMessageSync(msg);
1099 return NO_ERROR;
1100}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001101
Svetoslavd85084b2014-03-20 10:28:31 -07001102status_t SurfaceFlinger::clearAnimationFrameStats() {
1103 Mutex::Autolock _l(mStateLock);
1104 mAnimFrameTracker.clearStats();
1105 return NO_ERROR;
1106}
1107
1108status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1109 Mutex::Autolock _l(mStateLock);
1110 mAnimFrameTracker.getStats(outStats);
1111 return NO_ERROR;
1112}
1113
Dan Stozac4f471e2016-03-24 09:31:08 -07001114status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1115 HdrCapabilities* outCapabilities) const {
1116 Mutex::Autolock _l(mStateLock);
1117
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001118 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001119 if (displayDevice == nullptr) {
1120 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1121 return BAD_VALUE;
1122 }
1123
Peiyong Linfb069302018-04-25 14:34:31 -07001124 // At this point the DisplayDeivce should already be set up,
1125 // meaning the luminance information is already queried from
1126 // hardware composer and stored properly.
1127 const HdrCapabilities& capabilities = displayDevice->getHdrCapabilities();
1128 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1129 capabilities.getDesiredMaxLuminance(),
1130 capabilities.getDesiredMaxAverageLuminance(),
1131 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001132
1133 return NO_ERROR;
1134}
1135
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001136status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001137 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1138 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001139
Chia-I Wu90f669f2017-10-05 14:24:41 -07001140 if (mInjectVSyncs == enable) {
1141 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001142 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001143
1144 if (enable) {
1145 ALOGV("VSync Injections enabled");
1146 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001147 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique0fcde1b2017-12-20 16:50:21 -08001148 mInjectorEventThread =
1149 std::make_unique<impl::EventThread>(mVSyncInjector.get(), *this, false,
1150 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001151 }
Lloyd Pique9123ae52018-01-22 17:14:00 -08001152 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001153 } else {
1154 ALOGV("VSync Injections disabled");
Lloyd Pique9123ae52018-01-22 17:14:00 -08001155 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001156 }
1157
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001158 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001159 });
1160 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001161 return NO_ERROR;
1162}
1163
1164status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001165 Mutex::Autolock _l(mStateLock);
1166
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001167 if (!mInjectVSyncs) {
1168 ALOGE("VSync Injections not enabled");
1169 return BAD_VALUE;
1170 }
1171 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1172 ALOGV("Injecting VSync inside SurfaceFlinger");
1173 mVSyncInjector->onInjectSyncEvent(when);
1174 }
1175 return NO_ERROR;
1176}
1177
Lloyd Pique755e3192018-01-31 16:46:15 -08001178status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1179 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001180 IPCThreadState* ipc = IPCThreadState::self();
1181 const int pid = ipc->getCallingPid();
1182 const int uid = ipc->getCallingUid();
1183 if ((uid != AID_SHELL) &&
1184 !PermissionCache::checkPermission(sDump, pid, uid)) {
1185 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1186 return PERMISSION_DENIED;
1187 }
1188
1189 // Try to acquire a lock for 1s, fail gracefully
1190 const status_t err = mStateLock.timedLock(s2ns(1));
1191 const bool locked = (err == NO_ERROR);
1192 if (!locked) {
1193 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1194 return TIMED_OUT;
1195 }
1196
1197 outLayers->clear();
1198 mCurrentState.traverseInZOrder([&](Layer* layer) {
1199 outLayers->push_back(layer->getLayerDebugInfo());
1200 });
1201
1202 mStateLock.unlock();
1203 return NO_ERROR;
1204}
1205
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001206// ----------------------------------------------------------------------------
1207
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001208sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1209 ISurfaceComposer::VsyncSource vsyncSource) {
1210 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1211 return mSFEventThread->createEventConnection();
1212 } else {
1213 return mEventThread->createEventConnection();
1214 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001215}
1216
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001217// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001218
1219void SurfaceFlinger::waitForEvent() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001220 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001221}
1222
1223void SurfaceFlinger::signalTransaction() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001224 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001225}
1226
1227void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001228 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001229}
1230
1231void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001232 mRefreshPending = true;
Lloyd Pique9123ae52018-01-22 17:14:00 -08001233 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001234}
1235
1236status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001237 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001238 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001239}
1240
1241status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001242 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001243 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001244 if (res == NO_ERROR) {
1245 msg->wait();
1246 }
1247 return res;
1248}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001249
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001250void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001251 do {
1252 waitForEvent();
1253 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001254}
1255
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001256void SurfaceFlinger::enableHardwareVsync() {
1257 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001258 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001259 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001260 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1261 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001262 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001263 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001264}
1265
Jesse Hall948fe0c2013-10-14 12:56:09 -07001266void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001267 Mutex::Autolock _l(mHWVsyncLock);
1268
Jesse Hall948fe0c2013-10-14 12:56:09 -07001269 if (makeAvailable) {
1270 mHWVsyncAvailable = true;
1271 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001272 // Hardware vsync is not currently available, so abort the resync
1273 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001274 return;
1275 }
1276
David Sodman105b7dc2017-11-04 20:28:14 -07001277 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001278 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001279
1280 mPrimaryDispSync.reset();
1281 mPrimaryDispSync.setPeriod(period);
1282
1283 if (!mPrimaryHWVsyncEnabled) {
1284 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001285 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1286 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001287 mPrimaryHWVsyncEnabled = true;
1288 }
1289}
1290
Jesse Hall948fe0c2013-10-14 12:56:09 -07001291void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001292 Mutex::Autolock _l(mHWVsyncLock);
1293 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001294 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1295 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001296 mPrimaryDispSync.endResync();
1297 mPrimaryHWVsyncEnabled = false;
1298 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001299 if (makeUnavailable) {
1300 mHWVsyncAvailable = false;
1301 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001302}
1303
Tim Murray4a4e4a22016-04-19 16:29:23 +00001304void SurfaceFlinger::resyncWithRateLimit() {
1305 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001306
1307 // No explicit locking is needed here since EventThread holds a lock while calling this method
1308 static nsecs_t sLastResyncAttempted = 0;
1309 const nsecs_t now = systemTime();
1310 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001311 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001312 }
Dan Stoza57164302017-05-08 14:03:54 -07001313 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001314}
1315
Steven Thomasb02664d2017-07-26 18:48:28 -07001316void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1317 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001318 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001319 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001320 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001321 return;
1322 }
1323
1324 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001325 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001326 return;
1327 }
1328
Jamie Gennisd1700752013-10-14 12:22:52 -07001329 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001330
Jamie Gennisd1700752013-10-14 12:22:52 -07001331 { // Scope for the lock
1332 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001333 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001334 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001335 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001336 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001337
1338 if (needsHwVsync) {
1339 enableHardwareVsync();
1340 } else {
1341 disableHardwareVsync(false);
1342 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001343}
1344
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001345void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001346 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1347 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001348}
1349
Lloyd Pique715a2c12017-12-14 17:18:08 -08001350void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1351 HWC2::Connection connection) {
1352 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1353 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001354
Lloyd Piqueba04e622017-12-14 17:11:26 -08001355 // Ignore events that do not have the right sequenceId.
1356 if (sequenceId != getBE().mComposerSequenceId) {
1357 return;
1358 }
1359
Steven Thomasb02664d2017-07-26 18:48:28 -07001360 // Only lock if we're not on the main thread. This function is normally
1361 // called on a hwbinder thread, but for the primary display it's called on
1362 // the main thread with the state lock already held, so don't attempt to
1363 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001364 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001365
Lloyd Pique715a2c12017-12-14 17:18:08 -08001366 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001367
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001368 if (std::this_thread::get_id() == mMainThreadId) {
1369 // Process all pending hot plug events immediately if we are on the main thread.
1370 processDisplayHotplugEventsLocked();
1371 }
1372
Lloyd Piqueba04e622017-12-14 17:11:26 -08001373 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001374}
1375
Steven Thomasb02664d2017-07-26 18:48:28 -07001376void SurfaceFlinger::onRefreshReceived(int sequenceId,
1377 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001378 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001379 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001380 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001381 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001382 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001383}
1384
Dan Stoza9e56aa02015-11-02 13:00:03 -08001385void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001386 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001387 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001388 getHwComposer().setVsyncEnabled(disp,
1389 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001390}
1391
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001392// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001393void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001394 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001395 // Clear the drawing state so that the logic inside of
1396 // handleTransactionLocked will fire. It will determine the delta between
1397 // mCurrentState and mDrawingState and re-apply all changes when we make the
1398 // transition.
1399 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001400 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001401 mDisplays.clear();
1402}
1403
Steven Thomas050b2c82017-03-06 11:45:16 -08001404void SurfaceFlinger::updateVrFlinger() {
1405 if (!mVrFlinger)
1406 return;
1407 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001408 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001409 return;
1410 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001411
David Sodman105b7dc2017-11-04 20:28:14 -07001412 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001413 ALOGE("Vr flinger is only supported for remote hardware composer"
1414 " service connections. Ignoring request to transition to vr"
1415 " flinger.");
1416 mVrFlingerRequestsDisplay = false;
1417 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001418 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001419
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001420 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001421
Steven Thomasb02664d2017-07-26 18:48:28 -07001422 int currentDisplayPowerMode = getDisplayDeviceLocked(
1423 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001424
Steven Thomasb02664d2017-07-26 18:48:28 -07001425 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001426 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001427 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001428
Steven Thomasb02664d2017-07-26 18:48:28 -07001429 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001430 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001431 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1432 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001433 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001434
David Sodman105b7dc2017-11-04 20:28:14 -07001435 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1436 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001437
1438 if (vrFlingerRequestsDisplay) {
1439 mVrFlinger->GrantDisplayOwnership();
1440 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001441 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001442 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001443
1444 mVisibleRegionsDirty = true;
1445 invalidateHwcGeometry();
1446
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001447 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001448 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1449 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1450 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001451
Steven Thomasb02664d2017-07-26 18:48:28 -07001452 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001453 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001454 const nsecs_t period = activeConfig->getVsyncPeriod();
1455 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001456
Steven Thomasb02664d2017-07-26 18:48:28 -07001457 // Use phase of 0 since phase is not known.
1458 // Use latency of 0, which will snap to the ideal latency.
1459 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001460
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001461 android_atomic_or(1, &mRepaintEverything);
1462 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001463}
1464
Mathias Agopian4fec8732012-06-29 14:12:52 -07001465void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001466 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001467 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001468 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001469 bool frameMissed = !mHadClientComposition &&
1470 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001471 (mPreviousPresentFence->getSignalTime() ==
1472 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001473 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001474 if (mPropagateBackpressure && frameMissed) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001475 mTimeStats.incrementMissedFrames(true);
Dan Stoza50182882016-07-08 12:02:20 -07001476 signalLayerUpdate();
1477 break;
1478 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001479 if (frameMissed) {
1480 mTimeStats.incrementMissedFrames(false);
1481 }
Dan Stoza50182882016-07-08 12:02:20 -07001482
Steven Thomas050b2c82017-03-06 11:45:16 -08001483 // Now that we're going to make it to the handleMessageTransaction()
1484 // call below it's safe to call updateVrFlinger(), which will
1485 // potentially trigger a display handoff.
1486 updateVrFlinger();
1487
Dan Stoza6b9454d2014-11-07 16:00:59 -08001488 bool refreshNeeded = handleMessageTransaction();
1489 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001490 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001491 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001492 // Signal a refresh if a transaction modified the window state,
1493 // a new buffer was latched, or if HWC has requested a full
1494 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001495 signalRefresh();
1496 }
1497 break;
1498 }
1499 case MessageQueue::REFRESH: {
1500 handleMessageRefresh();
1501 break;
1502 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001503 }
1504}
1505
Dan Stoza6b9454d2014-11-07 16:00:59 -08001506bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001507 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001508 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001509 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001510 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001511 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001512 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001513}
1514
Dan Stoza6b9454d2014-11-07 16:00:59 -08001515bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001516 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001517 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001518}
1519
1520void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001521 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001522
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001523 mRefreshPending = false;
1524
Pablo Ceballos40845df2016-01-25 17:41:15 -08001525 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001526
Brian Andersond6927fb2016-07-23 23:37:30 -07001527 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001528 rebuildLayerStacks();
1529 setUpHWComposer();
1530 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001531 doTracing("handleRefresh");
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001532 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001533 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001534 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001535
David Sodman105b7dc2017-11-04 20:28:14 -07001536 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001537
1538 mHadClientComposition = false;
1539 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1540 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1541 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001542 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001543 }
Dan Stoza2713c302018-03-28 17:07:36 -07001544 mVsyncModulator.setLastFrameUsedRenderEngine(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001545
Dan Stoza9e56aa02015-11-02 13:00:03 -08001546 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001547}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001548
Mathias Agopiancd60f992012-08-16 16:28:27 -07001549void SurfaceFlinger::doDebugFlashRegions()
1550{
1551 // is debugging enabled
1552 if (CC_LIKELY(!mDebugRegion))
1553 return;
1554
1555 const bool repaintEverything = mRepaintEverything;
1556 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1557 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001558 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001559 // transform the dirty region into this screen's coordinate space
1560 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1561 if (!dirtyRegion.isEmpty()) {
1562 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001563 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001564
1565 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001566 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001567 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001568 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1569
Mathias Agopianda27af92012-09-13 18:17:13 -07001570 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001571 }
1572 }
1573 }
1574
1575 postFramebuffer();
1576
1577 if (mDebugRegion > 1) {
1578 usleep(mDebugRegion * 1000);
1579 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001580
Dan Stoza9e56aa02015-11-02 13:00:03 -08001581 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001582 auto& displayDevice = mDisplays[displayId];
1583 if (!displayDevice->isDisplayOn()) {
1584 continue;
1585 }
1586
David Sodman105b7dc2017-11-04 20:28:14 -07001587 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1588 ALOGE_IF(result != NO_ERROR,
1589 "prepareFrame for display %zd failed:"
1590 " %d (%s)",
1591 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001592 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001593}
1594
Adrian Roos1e1a1282017-11-01 19:05:31 +01001595void SurfaceFlinger::doTracing(const char* where) {
1596 ATRACE_CALL();
1597 ATRACE_NAME(where);
1598 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001599 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001600 }
1601}
1602
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001603void SurfaceFlinger::logLayerStats() {
1604 ATRACE_CALL();
1605 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1606 int32_t hwcId = -1;
1607 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1608 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1609 if (displayDevice->isPrimary()) {
1610 hwcId = displayDevice->getHwcDisplayId();
1611 break;
1612 }
1613 }
1614 if (hwcId < 0) {
1615 ALOGE("LayerStats: Hmmm, no primary display?");
1616 return;
1617 }
1618 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1619 }
1620}
1621
Brian Andersond6927fb2016-07-23 23:37:30 -07001622void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001623{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001624 ATRACE_CALL();
1625 ALOGV("preComposition");
1626
Mathias Agopiancd60f992012-08-16 16:28:27 -07001627 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001628 mDrawingState.traverseInZOrder([&](Layer* layer) {
1629 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001630 needExtraInvalidate = true;
1631 }
Robert Carr2047fae2016-11-28 14:09:09 -08001632 });
1633
Mathias Agopiancd60f992012-08-16 16:28:27 -07001634 if (needExtraInvalidate) {
1635 signalLayerUpdate();
1636 }
1637}
1638
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001639void SurfaceFlinger::updateCompositorTiming(
1640 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1641 std::shared_ptr<FenceTime>& presentFenceTime) {
1642 // Update queue of past composite+present times and determine the
1643 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001644 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001645 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001646 while (!getBE().mCompositePresentTimes.empty()) {
1647 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001648 // Cached values should have been updated before calling this method,
1649 // which helps avoid duplicate syscalls.
1650 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1651 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1652 break;
1653 }
1654 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001655 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001656 }
1657
1658 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001659 while (getBE().mCompositePresentTimes.size() > 16) {
1660 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001661 }
1662
Brian Andersond0010582017-03-07 13:20:31 -08001663 setCompositorTimingSnapped(
1664 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1665}
1666
1667void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1668 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001669 // Integer division and modulo round toward 0 not -inf, so we need to
1670 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001671 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001672 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1673 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1674
Brian Andersond0010582017-03-07 13:20:31 -08001675 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1676 if (idealLatency <= 0) {
1677 idealLatency = vsyncInterval;
1678 }
1679
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001680 // Snap the latency to a value that removes scheduling jitter from the
1681 // composition and present times, which often have >1ms of jitter.
1682 // Reducing jitter is important if an app attempts to extrapolate
1683 // something (such as user input) to an accurate diasplay time.
1684 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1685 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001686 nsecs_t bias = vsyncInterval / 2;
1687 int64_t extraVsyncs =
1688 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1689 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1690 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001691
David Sodman99974d22017-11-28 12:04:33 -08001692 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1693 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1694 getBE().mCompositorTiming.interval = vsyncInterval;
1695 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001696}
1697
1698void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001699{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001700 ATRACE_CALL();
1701 ALOGV("postComposition");
1702
Brian Anderson3546a3f2016-07-14 11:51:14 -07001703 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001704 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001705 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001706 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001707 }
1708
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001709 // |mStateLock| not needed as we are on the main thread
1710 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001711
David Sodman73beded2017-11-15 11:56:06 -08001712 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001713 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001714 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001715 glCompositionDoneFenceTime =
1716 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001717 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001718 } else {
1719 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1720 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001721
David Sodman73beded2017-11-15 11:56:06 -08001722 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001723 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001724 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001725 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001726
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001727 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1728 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1729
1730 // We use the refreshStartTime which might be sampled a little later than
1731 // when we started doing work for this frame, but that should be okay
1732 // since updateCompositorTiming has snapping logic.
1733 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001734 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001735 CompositorTiming compositorTiming;
1736 {
David Sodman99974d22017-11-28 12:04:33 -08001737 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1738 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001739 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001740
Robert Carr2047fae2016-11-28 14:09:09 -08001741 mDrawingState.traverseInZOrder([&](Layer* layer) {
1742 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001743 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001744 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001745 recordBufferingStats(layer->getName().string(),
1746 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001747 }
Robert Carr2047fae2016-11-28 14:09:09 -08001748 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001749
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001750 if (presentFenceTime->isValid()) {
1751 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001752 enableHardwareVsync();
1753 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001754 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001755 }
1756 }
1757
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001758 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001759 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001760 enableHardwareVsync();
1761 }
1762 }
1763
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001764 if (mAnimCompositionPending) {
1765 mAnimCompositionPending = false;
1766
Brian Anderson4e606e32017-03-16 15:34:57 -07001767 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001768 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001769 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001770 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001771 // The HWC doesn't support present fences, so use the refresh
1772 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001773 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001774 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001775 mAnimFrameTracker.setActualPresentTime(presentTime);
1776 }
1777 mAnimFrameTracker.advanceFrame();
1778 }
Dan Stozab90cf072015-03-05 11:05:59 -08001779
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001780 mTimeStats.incrementTotalFrames();
1781 if (mHadClientComposition) {
1782 mTimeStats.incrementClientCompositionFrames();
1783 }
1784
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001785 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1786 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001787 return;
1788 }
1789
1790 nsecs_t currentTime = systemTime();
1791 if (mHasPoweredOff) {
1792 mHasPoweredOff = false;
1793 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001794 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001795 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001796 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1797 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001798 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001799 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001800 }
David Sodman4a36e932017-11-07 14:29:47 -08001801 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001802 }
David Sodman4a36e932017-11-07 14:29:47 -08001803 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001804}
1805
1806void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001807 ATRACE_CALL();
1808 ALOGV("rebuildLayerStacks");
1809
Mathias Agopiancd60f992012-08-16 16:28:27 -07001810 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001811 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001812 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001813 mVisibleRegionsDirty = false;
1814 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001815
Jeff Sharkey76488112017-02-27 14:15:18 -07001816 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1817 Region opaqueRegion;
1818 Region dirtyRegion;
1819 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001820 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001821 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1822 const Transform& tr(displayDevice->getTransform());
1823 const Rect bounds(displayDevice->getBounds());
1824 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001825 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001826
Jeff Sharkey76488112017-02-27 14:15:18 -07001827 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001828 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001829 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1830 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001831 Region drawRegion(tr.transform(
1832 layer->visibleNonTransparentRegion));
1833 drawRegion.andSelf(bounds);
1834 if (!drawRegion.isEmpty()) {
1835 layersSortedByZ.add(layer);
1836 } else {
1837 // Clear out the HWC layer if this layer was
1838 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001839 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001840 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001841 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001842 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001843 // WM changes displayDevice->layerStack upon sleep/awake.
1844 // Here we make sure we delete the HWC layers even if
1845 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001846 hwcLayerDestroyed = layer->destroyHwcLayer(
1847 displayDevice->getHwcDisplayId());
1848 }
1849
1850 // If a layer is not going to get a release fence because
1851 // it is invisible, but it is also going to release its
1852 // old buffer, add it to the list of layers needing
1853 // fences.
1854 if (hwcLayerDestroyed) {
1855 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1856 mLayersWithQueuedFrames.cend(), layer);
1857 if (found != mLayersWithQueuedFrames.cend()) {
1858 layersNeedingFences.add(layer);
1859 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001860 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001861 });
1862 }
1863 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001864 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001865 displayDevice->undefinedRegion.set(bounds);
1866 displayDevice->undefinedRegion.subtractSelf(
1867 tr.transform(opaqueRegion));
1868 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001869 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001870 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001871}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001872
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001873// Returns a dataspace that fits all visible layers. The returned dataspace
1874// can only be one of
1875//
1876// - Dataspace::V0_SRGB
1877// - Dataspace::DISPLAY_P3
1878// - Dataspace::V0_SCRGB_LINEAR
1879// TODO(b/73825729) Add BT2020 data space.
1880ui::Dataspace SurfaceFlinger::getBestDataspace(
1881 const sp<const DisplayDevice>& displayDevice) const {
1882 Dataspace bestDataspace = Dataspace::V0_SRGB;
1883 for (const auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1884 switch (layer->getDataSpace()) {
1885 case Dataspace::V0_SCRGB:
1886 case Dataspace::V0_SCRGB_LINEAR:
1887 // return immediately
1888 return Dataspace::V0_SCRGB_LINEAR;
Peiyong Linf59a7192018-04-25 11:19:31 -07001889 case Dataspace::DISPLAY_P3:
1890 bestDataspace = Dataspace::DISPLAY_P3;
1891 break;
1892 // Historically, HDR dataspaces are ignored by SurfaceFlinger. But
1893 // since SurfaceFlinger simulates HDR support now, it should honor
1894 // them unless there is also native support.
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001895 case Dataspace::BT2020_PQ:
1896 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin62665892018-04-16 11:07:44 -07001897 if (!displayDevice->hasHDR10Support()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001898 return Dataspace::V0_SCRGB_LINEAR;
1899 }
1900 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001901 case Dataspace::BT2020_HLG:
1902 case Dataspace::BT2020_ITU_HLG:
1903 if (!displayDevice->hasHLGSupport()) {
1904 return Dataspace::V0_SCRGB_LINEAR;
1905 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001906 break;
1907 default:
1908 break;
1909 }
Romain Guy54f154a2017-10-24 21:40:32 +01001910 }
1911
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001912 return bestDataspace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001913}
1914
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001915// Pick the ColorMode / Dataspace for the display device.
1916// TODO(b/73825729) Add BT2020 color mode.
1917void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& displayDevice,
1918 ColorMode* outMode, Dataspace* outDataSpace) const {
1919 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1920 *outMode = ColorMode::NATIVE;
1921 *outDataSpace = Dataspace::UNKNOWN;
1922 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001923 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001924
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001925 switch (getBestDataspace(displayDevice)) {
1926 case Dataspace::DISPLAY_P3:
1927 case Dataspace::V0_SCRGB_LINEAR:
1928 *outMode = ColorMode::DISPLAY_P3;
1929 *outDataSpace = Dataspace::DISPLAY_P3;
1930 break;
1931 default:
1932 *outMode = ColorMode::SRGB;
1933 *outDataSpace = Dataspace::V0_SRGB;
1934 break;
1935 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001936}
1937
Mathias Agopiancd60f992012-08-16 16:28:27 -07001938void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001939 ATRACE_CALL();
1940 ALOGV("setUpHWComposer");
1941
Jesse Hall028dc8f2013-08-20 16:35:32 -07001942 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Dan Stozac7a25ad2018-04-12 11:45:09 -07001943 bool dirty = !mDisplays[dpy]->getDirtyRegion(mRepaintEverything).isEmpty();
Jesse Hallb7a05492014-08-14 15:45:06 -07001944 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1945 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1946
1947 // If nothing has changed (!dirty), don't recompose.
1948 // If something changed, but we don't currently have any visible layers,
1949 // and didn't when we last did a composition, then skip it this time.
1950 // The second rule does two things:
1951 // - When all layers are removed from a display, we'll emit one black
1952 // frame, then nothing more until we get new layers.
1953 // - When a display is created with a private layer stack, we won't
1954 // emit any black frames until a layer is added to the layer stack.
1955 bool mustRecompose = dirty && !(empty && wasEmpty);
1956
1957 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1958 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1959 mustRecompose ? "doing" : "skipping",
1960 dirty ? "+" : "-",
1961 empty ? "+" : "-",
1962 wasEmpty ? "+" : "-");
1963
Dan Stoza71433162014-02-04 16:22:36 -08001964 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001965
1966 if (mustRecompose) {
1967 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1968 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001969 }
1970
Dan Stoza9e56aa02015-11-02 13:00:03 -08001971 // build the h/w work list
1972 if (CC_UNLIKELY(mGeometryInvalid)) {
1973 mGeometryInvalid = false;
1974 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1975 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1976 const auto hwcId = displayDevice->getHwcDisplayId();
1977 if (hwcId >= 0) {
1978 const Vector<sp<Layer>>& currentLayers(
1979 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001980 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001981 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001982 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07001983 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001984 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001985 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001986 }
1987 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001988
Robert Carrae060832016-11-28 10:51:00 -08001989 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001990 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001991 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001992 }
1993 }
1994 }
1995 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001996 }
Riley Andrews03414a12014-07-01 14:22:59 -07001997
Dan Stoza9e56aa02015-11-02 13:00:03 -08001998 // Set the per-frame data
1999 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2000 auto& displayDevice = mDisplays[displayId];
2001 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002002
Dan Stoza9e56aa02015-11-02 13:00:03 -08002003 if (hwcId < 0) {
2004 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07002005 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07002006 if (mDrawingState.colorMatrixChanged) {
2007 displayDevice->setColorTransform(mDrawingState.colorMatrix);
2008 status_t result = getBE().mHwc->setColorTransform(hwcId, mDrawingState.colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002009 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
2010 "display %zd: %d", displayId, result);
2011 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002012 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002013 if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2014 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Peiyong Lin62665892018-04-16 11:07:44 -07002015 !displayDevice->hasHDR10Support()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002016 layer->forceClientComposition(hwcId);
2017 }
Peiyong Linf59a7192018-04-25 11:19:31 -07002018 if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
2019 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
2020 !displayDevice->hasHLGSupport()) {
2021 layer->forceClientComposition(hwcId);
2022 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002023
chaviwc9232ed2017-11-14 15:31:15 -08002024 if (layer->getForceClientComposition(hwcId)) {
2025 ALOGV("[%s] Requesting Client composition", layer->getName().string());
2026 layer->setCompositionType(hwcId, HWC2::Composition::Client);
2027 continue;
2028 }
2029
Dan Stoza9e56aa02015-11-02 13:00:03 -08002030 layer->setPerFrameData(displayDevice);
2031 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002032
2033 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002034 ColorMode colorMode;
2035 Dataspace dataSpace;
2036 pickColorMode(displayDevice, &colorMode, &dataSpace);
2037 setActiveColorModeInternal(displayDevice, colorMode, dataSpace);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002038 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002039 }
2040
Chia-I Wu28f320b2018-05-03 11:02:56 -07002041 mDrawingState.colorMatrixChanged = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002042
Dan Stoza9e56aa02015-11-02 13:00:03 -08002043 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002044 auto& displayDevice = mDisplays[displayId];
2045 if (!displayDevice->isDisplayOn()) {
2046 continue;
2047 }
2048
David Sodman105b7dc2017-11-04 20:28:14 -07002049 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002050 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2051 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002052 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002053}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002054
Mathias Agopiancd60f992012-08-16 16:28:27 -07002055void SurfaceFlinger::doComposition() {
2056 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002057 ALOGV("doComposition");
2058
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002059 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002060 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002061 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002062 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002063 // transform the dirty region into this screen's coordinate space
2064 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002065
2066 // repaint the framebuffer (if needed)
2067 doDisplayComposition(hw, dirtyRegion);
2068
Mathias Agopiancd60f992012-08-16 16:28:27 -07002069 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002070 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002071 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002072 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002073 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002074}
2075
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002076void SurfaceFlinger::postFramebuffer()
2077{
Mathias Agopian841cde52012-03-01 15:44:37 -08002078 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002079 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002080
Mathias Agopiana44b0412011-10-16 18:46:35 -07002081 const nsecs_t now = systemTime();
2082 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002083
Dan Stoza9e56aa02015-11-02 13:00:03 -08002084 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2085 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002086 if (!displayDevice->isDisplayOn()) {
2087 continue;
2088 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002089 const auto hwcId = displayDevice->getHwcDisplayId();
2090 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002091 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002092 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002093 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002094 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002095 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002096 // The layer buffer from the previous frame (if any) is released
2097 // by HWC only when the release fence from this frame (if any) is
2098 // signaled. Always get the release fence from HWC first.
2099 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002100 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002101
2102 // If the layer was client composited in the previous frame, we
2103 // need to merge with the previous client target acquire fence.
2104 // Since we do not track that, always merge with the current
2105 // client target acquire fence when it is available, even though
2106 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002107 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002108 releaseFence = Fence::merge("LayerRelease", releaseFence,
2109 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002110 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002111
Dan Stoza9e56aa02015-11-02 13:00:03 -08002112 layer->onLayerDisplayed(releaseFence);
2113 }
Chia-I Wu83806892017-11-16 10:50:20 -08002114
2115 // We've got a list of layers needing fences, that are disjoint with
2116 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2117 // supply them with the present fence.
2118 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002119 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002120 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2121 layer->onLayerDisplayed(presentFence);
2122 }
2123 }
2124
Dan Stoza9e56aa02015-11-02 13:00:03 -08002125 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002126 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002127 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002128 }
2129
Mathias Agopiana44b0412011-10-16 18:46:35 -07002130 mLastSwapBufferTime = systemTime() - now;
2131 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002132
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002133 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002134 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2135 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2136 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2137 logFrameStats();
2138 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002139 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002140}
2141
Mathias Agopian87baae12012-07-31 12:38:26 -07002142void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002143{
Mathias Agopian841cde52012-03-01 15:44:37 -08002144 ATRACE_CALL();
2145
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002146 // here we keep a copy of the drawing state (that is the state that's
2147 // going to be overwritten by handleTransactionLocked()) outside of
2148 // mStateLock so that the side-effects of the State assignment
2149 // don't happen with mStateLock held (which can cause deadlocks).
2150 State drawingState(mDrawingState);
2151
Mathias Agopianca4d3602011-05-19 15:38:14 -07002152 Mutex::Autolock _l(mStateLock);
2153 const nsecs_t now = systemTime();
2154 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002155
Mathias Agopianca4d3602011-05-19 15:38:14 -07002156 // Here we're guaranteed that some transaction flags are set
2157 // so we can call handleTransactionLocked() unconditionally.
2158 // We call getTransactionFlags(), which will also clear the flags,
2159 // with mStateLock held to guarantee that mCurrentState won't change
2160 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002161
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002162 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002163 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002164 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002165
Mathias Agopianca4d3602011-05-19 15:38:14 -07002166 mLastTransactionTime = systemTime() - now;
2167 mDebugInTransaction = 0;
2168 invalidateHwcGeometry();
2169 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002170}
2171
Lloyd Pique715a2c12017-12-14 17:18:08 -08002172DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique09594832018-01-22 17:48:03 -08002173 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002174 // Figure out whether the event is for the primary display or an
2175 // external display by matching the Hwc display id against one for a
2176 // connected display. If we did not find a match, we then check what
2177 // displays are not already connected to determine the type. If we don't
2178 // have a connected primary display, we assume the new display is meant to
2179 // be the primary display, and then if we don't have an external display,
2180 // we assume it is that.
2181 const auto primaryDisplayId =
2182 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2183 const auto externalDisplayId =
2184 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2185 if (primaryDisplayId && primaryDisplayId == display) {
2186 return DisplayDevice::DISPLAY_PRIMARY;
2187 } else if (externalDisplayId && externalDisplayId == display) {
2188 return DisplayDevice::DISPLAY_EXTERNAL;
2189 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2190 return DisplayDevice::DISPLAY_PRIMARY;
2191 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2192 return DisplayDevice::DISPLAY_EXTERNAL;
2193 }
2194
2195 return DisplayDevice::DISPLAY_ID_INVALID;
2196}
2197
Lloyd Piqueba04e622017-12-14 17:11:26 -08002198void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2199 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002200 auto displayType = determineDisplayType(event.display, event.connection);
2201 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2202 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2203 continue;
2204 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002205
2206 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2207 ALOGE("External displays are not supported by the vr hardware composer.");
2208 continue;
2209 }
2210
Lloyd Pique715a2c12017-12-14 17:18:08 -08002211 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002212
2213 if (event.connection == HWC2::Connection::Connected) {
Steven Thomas3bed0522018-03-20 15:40:48 -07002214 if (!mBuiltinDisplays[displayType].get()) {
2215 ALOGV("Creating built in display %d", displayType);
2216 mBuiltinDisplays[displayType] = new BBinder();
2217 // All non-virtual displays are currently considered secure.
2218 DisplayDeviceState info(displayType, true);
2219 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2220 "Built-in Screen" : "External Screen";
2221 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
Lloyd Pique4d234852018-01-22 17:21:36 -08002222 mInterceptor->saveDisplayCreation(info);
Steven Thomas3bed0522018-03-20 15:40:48 -07002223 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002224 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002225 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002226
Lloyd Piquefcd86612017-12-14 17:15:36 -08002227 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2228 if (idx >= 0) {
2229 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Lloyd Pique4d234852018-01-22 17:21:36 -08002230 mInterceptor->saveDisplayDeletion(info.displayId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002231 mCurrentState.displays.removeItemsAt(idx);
2232 }
2233 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002234 }
2235
2236 processDisplayChangesLocked();
2237 }
2238
2239 mPendingHotplugEvents.clear();
2240}
2241
Lloyd Pique09594832018-01-22 17:48:03 -08002242sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2243 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2244 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002245 bool hasWideColorGamut = false;
Lloyd Pique09594832018-01-22 17:48:03 -08002246 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002247 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Lloyd Pique09594832018-01-22 17:48:03 -08002248 for (ColorMode colorMode : modes) {
2249 switch (colorMode) {
2250 case ColorMode::DISPLAY_P3:
2251 case ColorMode::ADOBE_RGB:
2252 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002253 hasWideColorGamut = true;
Lloyd Pique09594832018-01-22 17:48:03 -08002254 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002255 // TODO(lpy) Handle BT2020, BT2100_PQ and BT2100_HLG properly.
Lloyd Pique09594832018-01-22 17:48:03 -08002256 default:
2257 break;
2258 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002259
2260 std::vector<RenderIntent> renderIntents = getHwComposer().getRenderIntents(hwcId,
2261 colorMode);
2262 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2263 for (auto intent : renderIntents) {
2264 if (intent == RenderIntent::ENHANCE) {
2265 mBuiltinDisplaySupportsEnhance = true;
2266 break;
2267 }
2268 }
2269 }
Lloyd Pique09594832018-01-22 17:48:03 -08002270 }
2271 }
2272
Peiyong Lin62665892018-04-16 11:07:44 -07002273 HdrCapabilities hdrCapabilities;
2274 getHwComposer().getHdrCapabilities(hwcId, &hdrCapabilities);
Lloyd Pique09594832018-01-22 17:48:03 -08002275
2276 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2277 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2278
2279 /*
2280 * Create our display's surface
2281 */
2282 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2283 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
2284 renderSurface->setAsync(state.type >= DisplayDevice::DISPLAY_VIRTUAL);
2285 renderSurface->setNativeWindow(nativeWindow.get());
2286 const int displayWidth = renderSurface->queryWidth();
2287 const int displayHeight = renderSurface->queryHeight();
2288
2289 // Make sure that composition can never be stalled by a virtual display
2290 // consumer that isn't processing buffers fast enough. We have to do this
2291 // in two places:
2292 // * Here, in case the display is composed entirely by HWC.
2293 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2294 // window's swap interval in eglMakeCurrent, so they'll override the
2295 // interval we set here.
2296 if (state.type >= DisplayDevice::DISPLAY_VIRTUAL) {
2297 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2298 }
2299
2300 // virtual displays are always considered enabled
2301 auto initialPowerMode = (state.type >= DisplayDevice::DISPLAY_VIRTUAL) ? HWC_POWER_MODE_NORMAL
2302 : HWC_POWER_MODE_OFF;
2303
2304 sp<DisplayDevice> hw =
2305 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2306 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
Peiyong Lin2c327ac2018-04-19 22:06:34 -07002307 hasWideColorGamut, hdrCapabilities,
2308 getHwComposer().getSupportedPerFrameMetadata(hwcId),
2309 initialPowerMode);
Lloyd Pique09594832018-01-22 17:48:03 -08002310
2311 if (maxFrameBufferAcquiredBuffers >= 3) {
2312 nativeWindowSurface->preallocateBuffers();
2313 }
2314
2315 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002316 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2317 if (hasWideColorGamut) {
Lloyd Pique09594832018-01-22 17:48:03 -08002318 defaultColorMode = ColorMode::SRGB;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002319 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique09594832018-01-22 17:48:03 -08002320 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002321 setActiveColorModeInternal(hw, defaultColorMode, defaultDataSpace);
Lloyd Pique09594832018-01-22 17:48:03 -08002322 hw->setLayerStack(state.layerStack);
2323 hw->setProjection(state.orientation, state.viewport, state.frame);
2324 hw->setDisplayName(state.displayName);
2325
2326 return hw;
2327}
2328
Lloyd Pique347200f2017-12-14 17:00:15 -08002329void SurfaceFlinger::processDisplayChangesLocked() {
2330 // here we take advantage of Vector's copy-on-write semantics to
2331 // improve performance by skipping the transaction entirely when
2332 // know that the lists are identical
2333 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2334 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2335 if (!curr.isIdenticalTo(draw)) {
2336 mVisibleRegionsDirty = true;
2337 const size_t cc = curr.size();
2338 size_t dc = draw.size();
2339
2340 // find the displays that were removed
2341 // (ie: in drawing state but not in current state)
2342 // also handle displays that changed
2343 // (ie: displays that are in both lists)
2344 for (size_t i = 0; i < dc;) {
2345 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2346 if (j < 0) {
2347 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002348 // Call makeCurrent() on the primary display so we can
2349 // be sure that nothing associated with this display
2350 // is current.
2351 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2352 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2353 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2354 if (hw != nullptr) hw->disconnect(getHwComposer());
2355 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2356 mEventThread->onHotplugReceived(draw[i].type, false);
2357 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002358 } else {
2359 // this display is in both lists. see if something changed.
2360 const DisplayDeviceState& state(curr[j]);
2361 const wp<IBinder>& display(curr.keyAt(j));
2362 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2363 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2364 if (state_binder != draw_binder) {
2365 // changing the surface is like destroying and
2366 // recreating the DisplayDevice, so we just remove it
2367 // from the drawing state, so that it get re-added
2368 // below.
2369 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2370 if (hw != nullptr) hw->disconnect(getHwComposer());
2371 mDisplays.removeItem(display);
2372 mDrawingState.displays.removeItemsAt(i);
2373 dc--;
2374 // at this point we must loop to the next item
2375 continue;
2376 }
2377
2378 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2379 if (disp != nullptr) {
2380 if (state.layerStack != draw[i].layerStack) {
2381 disp->setLayerStack(state.layerStack);
2382 }
2383 if ((state.orientation != draw[i].orientation) ||
2384 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2385 disp->setProjection(state.orientation, state.viewport, state.frame);
2386 }
2387 if (state.width != draw[i].width || state.height != draw[i].height) {
2388 disp->setDisplaySize(state.width, state.height);
2389 }
2390 }
2391 }
2392 ++i;
2393 }
2394
2395 // find displays that were added
2396 // (ie: in current state but not in drawing state)
2397 for (size_t i = 0; i < cc; i++) {
2398 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2399 const DisplayDeviceState& state(curr[i]);
2400
2401 sp<DisplaySurface> dispSurface;
2402 sp<IGraphicBufferProducer> producer;
2403 sp<IGraphicBufferProducer> bqProducer;
2404 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002405 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002406
2407 int32_t hwcId = -1;
2408 if (state.isVirtualDisplay()) {
2409 // Virtual displays without a surface are dormant:
2410 // they have external state (layer stack, projection,
2411 // etc.) but no internal state (i.e. a DisplayDevice).
2412 if (state.surface != nullptr) {
2413 // Allow VR composer to use virtual displays.
2414 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2415 int width = 0;
2416 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2417 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2418 int height = 0;
2419 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2420 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2421 int intFormat = 0;
2422 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2423 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002424 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002425
2426 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2427 }
2428
2429 // TODO: Plumb requested format back up to consumer
2430
2431 sp<VirtualDisplaySurface> vds =
2432 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2433 bqProducer, bqConsumer,
2434 state.displayName);
2435
2436 dispSurface = vds;
2437 producer = vds;
2438 }
2439 } else {
2440 ALOGE_IF(state.surface != nullptr,
2441 "adding a supported display, but rendering "
2442 "surface is provided (%p), ignoring it",
2443 state.surface.get());
2444
2445 hwcId = state.type;
2446 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2447 producer = bqProducer;
2448 }
2449
2450 const wp<IBinder>& display(curr.keyAt(i));
2451 if (dispSurface != nullptr) {
Lloyd Pique09594832018-01-22 17:48:03 -08002452 mDisplays.add(display,
2453 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2454 producer));
Lloyd Pique347200f2017-12-14 17:00:15 -08002455 if (!state.isVirtualDisplay()) {
2456 mEventThread->onHotplugReceived(state.type, true);
2457 }
2458 }
2459 }
2460 }
2461 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002462
2463 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002464}
2465
Mathias Agopian87baae12012-07-31 12:38:26 -07002466void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002467{
Dan Stoza7dde5992015-05-22 09:51:44 -07002468 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002469 mCurrentState.traverseInZOrder([](Layer* layer) {
2470 layer->notifyAvailableFrames();
2471 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002472
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002473 /*
2474 * Traversal of the children
2475 * (perform the transaction for each of them if needed)
2476 */
2477
Mathias Agopian3559b072012-08-15 13:46:03 -07002478 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002479 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002480 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002481 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002482
2483 const uint32_t flags = layer->doTransaction(0);
2484 if (flags & Layer::eVisibleRegion)
2485 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002486 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002487 }
2488
2489 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002490 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002491 */
2492
Mathias Agopiane57f2922012-08-09 16:29:12 -07002493 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002494 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002495 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002496 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002497
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002498 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002499 // The transform hint might have changed for some layers
2500 // (either because a display has changed, or because a layer
2501 // as changed).
2502 //
2503 // Walk through all the layers in currentLayers,
2504 // and update their transform hint.
2505 //
2506 // If a layer is visible only on a single display, then that
2507 // display is used to calculate the hint, otherwise we use the
2508 // default display.
2509 //
2510 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2511 // the hint is set before we acquire a buffer from the surface texture.
2512 //
2513 // NOTE: layer transactions have taken place already, so we use their
2514 // drawing state. However, SurfaceFlinger's own transaction has not
2515 // happened yet, so we must use the current state layer list
2516 // (soon to become the drawing state list).
2517 //
2518 sp<const DisplayDevice> disp;
2519 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002520 bool first = true;
2521 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002522 // NOTE: we rely on the fact that layers are sorted by
2523 // layerStack first (so we don't have to traverse the list
2524 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002525 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002526 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002527 currentlayerStack = layerStack;
2528 // figure out if this layerstack is mirrored
2529 // (more than one display) if so, pick the default display,
2530 // if not, pick the only display it's on.
2531 disp.clear();
2532 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2533 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002534 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002535 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002536 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002537 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002538 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002539 break;
2540 }
2541 }
2542 }
2543 }
Chet Haase91d25932013-04-11 15:24:55 -07002544
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002545 if (disp == nullptr) {
2546 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2547 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002548
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002549 // could be null when this layer is using a layerStack
2550 // that is not visible on any display. Also can occur at
2551 // screen off/on times.
2552 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002553 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002554
2555 // disp can be null if there is no display available at all to get
2556 // the transform hint from.
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002557 if (disp != nullptr) {
2558 layer->updateTransformHint(disp);
2559 }
Robert Carr2047fae2016-11-28 14:09:09 -08002560
2561 first = false;
2562 });
Mathias Agopian84300952012-11-21 16:02:13 -08002563 }
2564
2565
Mathias Agopian3559b072012-08-15 13:46:03 -07002566 /*
2567 * Perform our own transaction if needed
2568 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002569
2570 if (mLayersAdded) {
2571 mLayersAdded = false;
2572 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002573 mVisibleRegionsDirty = true;
2574 }
2575
2576 // some layers might have been removed, so
2577 // we need to update the regions they're exposing.
2578 if (mLayersRemoved) {
2579 mLayersRemoved = false;
2580 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002581 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002582 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002583 // this layer is not visible anymore
2584 // TODO: we could traverse the tree from front to back and
2585 // compute the actual visible region
2586 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002587 Region visibleReg;
2588 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002589 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002590 }
Robert Carr2047fae2016-11-28 14:09:09 -08002591 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002592 }
2593
2594 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002595
2596 updateCursorAsync();
2597}
2598
2599void SurfaceFlinger::updateCursorAsync()
2600{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002601 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2602 auto& displayDevice = mDisplays[displayId];
2603 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002604 continue;
2605 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002606
2607 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2608 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002609 }
2610 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002611}
2612
2613void SurfaceFlinger::commitTransaction()
2614{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002615 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002616 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002617 for (const auto& l : mLayersPendingRemoval) {
2618 recordBufferingStats(l->getName().string(),
2619 l->getOccupancyHistory(true));
2620 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002621 }
2622 mLayersPendingRemoval.clear();
2623 }
2624
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002625 // If this transaction is part of a window animation then the next frame
2626 // we composite should be considered an animation as well.
2627 mAnimCompositionPending = mAnimTransactionPending;
2628
Mathias Agopian4fec8732012-06-29 14:12:52 -07002629 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002630 // clear the "changed" flags in current state
2631 mCurrentState.colorMatrixChanged = false;
2632
Robert Carr1f0a16a2016-10-24 16:27:39 -07002633 mDrawingState.traverseInZOrder([](Layer* layer) {
2634 layer->commitChildList();
2635 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002636 mTransactionPending = false;
2637 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002638 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002639}
2640
Chia-I Wuab0c3192017-08-01 11:29:00 -07002641void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002642 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002643{
Mathias Agopian841cde52012-03-01 15:44:37 -08002644 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002645 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002646
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002647 Region aboveOpaqueLayers;
2648 Region aboveCoveredLayers;
2649 Region dirty;
2650
Mathias Agopian87baae12012-07-31 12:38:26 -07002651 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002652
Robert Carr2047fae2016-11-28 14:09:09 -08002653 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002654 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002655 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002656
Jesse Hall01e29052013-02-19 16:13:35 -08002657 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002658 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002659 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002660
Mathias Agopianab028732010-03-16 16:41:46 -07002661 /*
2662 * opaqueRegion: area of a surface that is fully opaque.
2663 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002664 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002665
2666 /*
2667 * visibleRegion: area of a surface that is visible on screen
2668 * and not fully transparent. This is essentially the layer's
2669 * footprint minus the opaque regions above it.
2670 * Areas covered by a translucent surface are considered visible.
2671 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002672 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002673
2674 /*
2675 * coveredRegion: area of a surface that is covered by all
2676 * visible regions above it (which includes the translucent areas).
2677 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002678 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002679
Jesse Halla8026d22012-09-25 13:25:04 -07002680 /*
2681 * transparentRegion: area of a surface that is hinted to be completely
2682 * transparent. This is only used to tell when the layer has no visible
2683 * non-transparent regions and can be removed from the layer list. It
2684 * does not affect the visibleRegion of this layer or any layers
2685 * beneath it. The hint may not be correct if apps don't respect the
2686 * SurfaceView restrictions (which, sadly, some don't).
2687 */
2688 Region transparentRegion;
2689
Mathias Agopianab028732010-03-16 16:41:46 -07002690
2691 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002692 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002693 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002694 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002695 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002696 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002697 if (!visibleRegion.isEmpty()) {
2698 // Remove the transparent area from the visible region
2699 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002700 if (tr.preserveRects()) {
2701 // transform the transparent region
2702 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002703 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002704 // transformation too complex, can't do the
2705 // transparent region optimization.
2706 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002707 }
Mathias Agopianab028732010-03-16 16:41:46 -07002708 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002709
Mathias Agopianab028732010-03-16 16:41:46 -07002710 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002711 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002712 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002713 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2714 // the opaque region is the layer's footprint
2715 opaqueRegion = visibleRegion;
2716 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002717 }
2718 }
2719
Robert Carre5f4f692018-01-12 13:12:28 -08002720 if (visibleRegion.isEmpty()) {
2721 layer->clearVisibilityRegions();
2722 return;
2723 }
2724
Mathias Agopianab028732010-03-16 16:41:46 -07002725 // Clip the covered region to the visible region
2726 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2727
2728 // Update aboveCoveredLayers for next (lower) layer
2729 aboveCoveredLayers.orSelf(visibleRegion);
2730
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002731 // subtract the opaque region covered by the layers above us
2732 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002733
2734 // compute this layer's dirty region
2735 if (layer->contentDirty) {
2736 // we need to invalidate the whole region
2737 dirty = visibleRegion;
2738 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002739 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002740 layer->contentDirty = false;
2741 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002742 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002743 * the exposed region consists of two components:
2744 * 1) what's VISIBLE now and was COVERED before
2745 * 2) what's EXPOSED now less what was EXPOSED before
2746 *
2747 * note that (1) is conservative, we start with the whole
2748 * visible region but only keep what used to be covered by
2749 * something -- which mean it may have been exposed.
2750 *
2751 * (2) handles areas that were not covered by anything but got
2752 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002753 */
Mathias Agopianab028732010-03-16 16:41:46 -07002754 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002755 const Region oldVisibleRegion = layer->visibleRegion;
2756 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002757 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2758 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002759 }
2760 dirty.subtractSelf(aboveOpaqueLayers);
2761
2762 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002763 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002764
Mathias Agopianab028732010-03-16 16:41:46 -07002765 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002766 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002767
Jesse Halla8026d22012-09-25 13:25:04 -07002768 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002769 layer->setVisibleRegion(visibleRegion);
2770 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002771 layer->setVisibleNonTransparentRegion(
2772 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002773 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002774
Mathias Agopian87baae12012-07-31 12:38:26 -07002775 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002776}
2777
Chia-I Wuab0c3192017-08-01 11:29:00 -07002778void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002779 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002780 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002781 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002782 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002783 }
2784 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002785}
2786
Dan Stoza6b9454d2014-11-07 16:00:59 -08002787bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002788{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002789 ALOGV("handlePageFlip");
2790
Brian Andersond6927fb2016-07-23 23:37:30 -07002791 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002792
Mathias Agopian4fec8732012-06-29 14:12:52 -07002793 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002794 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002795 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002796
2797 // Store the set of layers that need updates. This set must not change as
2798 // buffers are being latched, as this could result in a deadlock.
2799 // Example: Two producers share the same command stream and:
2800 // 1.) Layer 0 is latched
2801 // 2.) Layer 0 gets a new frame
2802 // 2.) Layer 1 gets a new frame
2803 // 3.) Layer 1 is latched.
2804 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2805 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002806 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002807 if (layer->hasQueuedFrame()) {
2808 frameQueued = true;
2809 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002810 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002811 } else {
2812 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002813 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002814 } else {
2815 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002816 }
Robert Carr2047fae2016-11-28 14:09:09 -08002817 });
2818
Dan Stoza9e56aa02015-11-02 13:00:03 -08002819 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002820 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002821 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002822 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002823 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002824 newDataLatched = true;
2825 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002826 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002827
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002828 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002829
2830 // If we will need to wake up at some time in the future to deal with a
2831 // queued frame that shouldn't be displayed during this vsync period, wake
2832 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002833 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002834 signalLayerUpdate();
2835 }
2836
2837 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002838 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002839}
2840
Mathias Agopianad456f92011-01-13 17:53:01 -08002841void SurfaceFlinger::invalidateHwcGeometry()
2842{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002843 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002844}
2845
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002846
Fabien Sanglard830b8472016-11-30 16:35:58 -08002847void SurfaceFlinger::doDisplayComposition(
2848 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002849 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002850{
Dan Stoza71433162014-02-04 16:22:36 -08002851 // We only need to actually compose the display if:
2852 // 1) It is being handled by hardware composer, which may need this to
2853 // keep its virtual display state machine in sync, or
2854 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002855 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002856 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002857 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002858 return;
2859 }
2860
Dan Stoza9e56aa02015-11-02 13:00:03 -08002861 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002862 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002863
2864 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002865 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002866}
2867
Chia-I Wub02087d2017-11-09 10:19:54 -08002868bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002869{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002870 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002871
Chia-I Wub02087d2017-11-09 10:19:54 -08002872 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002873 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002874 const auto hwcId = displayDevice->getHwcDisplayId();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002875 const bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
2876 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
2877 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2878 HWC2::Capability::SkipClientColorTransform);
2879 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002880
2881 mat4 oldColorMatrix;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002882 mat4 legacySrgbSaturationMatrix = mLegacySrgbSaturationMatrix;
2883 const bool applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002884 if (applyColorMatrix) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07002885 oldColorMatrix = getRenderEngine().setupColorTransform(mDrawingState.colorMatrix);
2886 legacySrgbSaturationMatrix = mDrawingState.colorMatrix * legacySrgbSaturationMatrix;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002887 }
2888
Dan Stoza9e56aa02015-11-02 13:00:03 -08002889 if (hasClientComposition) {
2890 ALOGV("hasClientComposition");
2891
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002892 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002893 if (displayDevice->hasWideColorGamut()) {
2894 outputDataspace = displayDevice->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002895 }
2896 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002897 getBE().mRenderEngine->setDisplayMaxLuminance(
2898 displayDevice->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002899
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();
2961 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002962 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002963 bool firstLayer = true;
2964 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002965 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002966 displayTransform.transform(layer->visibleRegion)));
2967 ALOGV("Layer: %s", layer->getName().string());
2968 ALOGV(" Composition type: %s",
2969 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002970 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002971 switch (layer->getCompositionType(hwcId)) {
2972 case HWC2::Composition::Cursor:
2973 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002974 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002975 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002976 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002977 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002978 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002979 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002980 // never clear the very first layer since we're
2981 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002982 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002983 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002984 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002985 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002986 case HWC2::Composition::Client: {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002987 // Only apply saturation matrix layer that is legacy SRGB dataspace
2988 // when auto color mode is on.
2989 bool restore = false;
2990 mat4 savedMatrix;
2991 if (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
Chia-I Wu11481472018-05-04 10:43:19 -07002992 layer->isLegacyDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002993 savedMatrix =
2994 getRenderEngine().setupColorTransform(legacySrgbSaturationMatrix);
2995 restore = true;
2996 }
chaviwa76b2712017-09-20 12:02:26 -07002997 layer->draw(renderArea, clip);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002998 if (restore) {
2999 getRenderEngine().setupColorTransform(savedMatrix);
3000 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003001 break;
3002 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003003 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07003004 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003005 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003006 } else {
3007 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003008 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003009 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003010 }
3011 } else {
3012 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08003013 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08003014 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08003015 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07003016 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07003017 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07003018 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003019 }
3020 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003021
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003022 if (applyColorMatrix) {
3023 getRenderEngine().setupColorTransform(oldColorMatrix);
3024 }
3025
Mathias Agopianf45c5102012-10-24 16:29:17 -07003026 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003027 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003028 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003029}
3030
Fabien Sanglard830b8472016-11-30 16:35:58 -08003031void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
3032 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003033 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003034 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003035}
3036
Dan Stoza7d89d062015-04-30 13:29:25 -07003037status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003038 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003039 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003040 const sp<Layer>& lbc,
3041 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003042{
Dan Stoza7d89d062015-04-30 13:29:25 -07003043 // add this layer to the current state list
3044 {
3045 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003046 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003047 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3048 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003049 return NO_MEMORY;
3050 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003051 if (parent == nullptr) {
3052 mCurrentState.layersSortedByZ.add(lbc);
3053 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003054 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003055 ALOGE("addClientLayer called with a removed parent");
3056 return NAME_NOT_FOUND;
3057 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003058 parent->addChild(lbc);
3059 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003060
Dan Stoza101d8dc2018-02-27 15:42:25 -08003061 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
Dan Stoza0a0158c2018-03-16 13:38:54 -07003062 // TODO (b/74616334): Change this back to a fatal assert once the leak is fixed
3063 ALOGE_IF(mGraphicBufferProducerList.size() > mMaxGraphicBufferProducerListSize,
3064 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3065 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize,
3066 mNumLayers);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003067 mLayersAdded = true;
3068 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003069 }
3070
Mathias Agopian96f08192010-06-02 23:28:45 -07003071 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003072 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003073
Dan Stoza7d89d062015-04-30 13:29:25 -07003074 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003075}
3076
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003077status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003078 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003079 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3080}
Robert Carr7f9b8992017-03-10 11:08:39 -08003081
chaviwca27f252018-02-06 16:46:39 -08003082status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3083 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003084 if (layer->isPendingRemoval()) {
3085 return NO_ERROR;
3086 }
3087
Robert Carr1f0a16a2016-10-24 16:27:39 -07003088 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003089 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003090 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003091 if (topLevelOnly) {
3092 return NO_ERROR;
3093 }
3094
Chia-I Wu98f1c102017-05-30 14:54:08 -07003095 sp<Layer> ancestor = p;
3096 while (ancestor->getParent() != nullptr) {
3097 ancestor = ancestor->getParent();
3098 }
3099 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3100 ALOGE("removeLayer called with a layer whose parent has been removed");
3101 return NAME_NOT_FOUND;
3102 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003103
3104 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003105 } else {
3106 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003107 }
3108
Robert Carr136e2f62017-02-08 17:54:29 -08003109 // As a matter of normal operation, the LayerCleaner will produce a second
3110 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3111 // so we will succeed in promoting it, but it's already been removed
3112 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3113 // otherwise something has gone wrong and we are leaking the layer.
3114 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003115 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3116 layer->getName().string(),
3117 (p != nullptr) ? p->getName().string() : "no-parent");
3118 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003119 } else if (index < 0) {
3120 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003121 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003122
Chia-I Wuc6657022017-08-15 11:18:17 -07003123 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003124 mLayersPendingRemoval.add(layer);
3125 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003126 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003127 setTransactionFlags(eTransactionNeeded);
3128 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003129}
3130
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003131uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003132 return android_atomic_release_load(&mTransactionFlags);
3133}
3134
Mathias Agopian3f844832013-08-07 21:24:32 -07003135uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003136 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3137}
3138
Mathias Agopian3f844832013-08-07 21:24:32 -07003139uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza2713c302018-03-28 17:07:36 -07003140 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3141}
3142
3143uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3144 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003145 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza2713c302018-03-28 17:07:36 -07003146 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003147 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003148 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003149 }
3150 return old;
3151}
3152
chaviwca27f252018-02-06 16:46:39 -08003153bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3154 for (const ComposerState& state : states) {
3155 // Here we need to check that the interface we're given is indeed
3156 // one of our own. A malicious client could give us a nullptr
3157 // IInterface, or one of its own or even one of our own but a
3158 // different type. All these situations would cause us to crash.
3159 if (state.client == nullptr) {
3160 return true;
3161 }
3162
3163 sp<IBinder> binder = IInterface::asBinder(state.client);
3164 if (binder == nullptr) {
3165 return true;
3166 }
3167
3168 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3169 return true;
3170 }
3171 }
3172 return false;
3173}
3174
Mathias Agopian8b33f032012-07-24 20:43:54 -07003175void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003176 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003177 const Vector<DisplayState>& displays,
3178 uint32_t flags)
3179{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003180 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003181 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003182 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003183
chaviwca27f252018-02-06 16:46:39 -08003184 if (containsAnyInvalidClientState(states)) {
3185 return;
3186 }
3187
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003188 if (flags & eAnimation) {
3189 // For window updates that are part of an animation we must wait for
3190 // previous animation "frames" to be handled.
3191 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003192 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003193 if (CC_UNLIKELY(err != NO_ERROR)) {
3194 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003195 // caller after a few seconds.
3196 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3197 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003198 mAnimTransactionPending = false;
3199 break;
3200 }
3201 }
3202 }
3203
chaviwca27f252018-02-06 16:46:39 -08003204 for (const DisplayState& display : displays) {
3205 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003206 }
3207
chaviwca27f252018-02-06 16:46:39 -08003208 for (const ComposerState& state : states) {
3209 transactionFlags |= setClientStateLocked(state);
3210 }
3211
3212 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3213 // as destroyed should only occur after setting all other states. This is to allow for a
3214 // child re-parent to happen before marking its original parent as destroyed (which would
3215 // then mark the child as destroyed).
3216 for (const ComposerState& state : states) {
3217 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003218 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003219
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003220 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3221 // anyway. This can be used as a flush mechanism for previous async transactions.
3222 // Empty animation transaction can be used to simulate back-pressure, so also force a
3223 // transaction for empty animation transactions.
3224 if (transactionFlags == 0 &&
3225 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003226 transactionFlags = eTransactionNeeded;
3227 }
3228
Mathias Agopian386aa982011-11-07 21:58:03 -08003229 if (transactionFlags) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003230 if (mInterceptor->isEnabled()) {
3231 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003232 }
Irvel468051e2016-06-13 16:44:44 -07003233
Mathias Agopian386aa982011-11-07 21:58:03 -08003234 // this triggers the transaction
Dan Stoza2713c302018-03-28 17:07:36 -07003235 const auto start = (flags & eEarlyWakeup)
3236 ? VSyncModulator::TransactionStart::EARLY
3237 : VSyncModulator::TransactionStart::NORMAL;
3238 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003239
3240 // if this is a synchronous transaction, wait for it to take effect
3241 // before returning.
3242 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003243 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003244 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003245 if (flags & eAnimation) {
3246 mAnimTransactionPending = true;
3247 }
3248 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003249 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3250 if (CC_UNLIKELY(err != NO_ERROR)) {
3251 // just in case something goes wrong in SF, return to the
3252 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003253 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3254 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003255 break;
3256 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003257 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003258 }
3259}
3260
Mathias Agopiane57f2922012-08-09 16:29:12 -07003261uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3262{
Jesse Hall9a143922012-10-04 16:29:19 -07003263 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3264 if (dpyIdx < 0)
3265 return 0;
3266
Mathias Agopiane57f2922012-08-09 16:29:12 -07003267 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003268 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003269 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003270 const uint32_t what = s.what;
3271 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003272 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003273 disp.surface = s.surface;
3274 flags |= eDisplayTransactionNeeded;
3275 }
3276 }
3277 if (what & DisplayState::eLayerStackChanged) {
3278 if (disp.layerStack != s.layerStack) {
3279 disp.layerStack = s.layerStack;
3280 flags |= eDisplayTransactionNeeded;
3281 }
3282 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003283 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003284 if (disp.orientation != s.orientation) {
3285 disp.orientation = s.orientation;
3286 flags |= eDisplayTransactionNeeded;
3287 }
3288 if (disp.frame != s.frame) {
3289 disp.frame = s.frame;
3290 flags |= eDisplayTransactionNeeded;
3291 }
3292 if (disp.viewport != s.viewport) {
3293 disp.viewport = s.viewport;
3294 flags |= eDisplayTransactionNeeded;
3295 }
3296 }
Michael Lentine47e45402014-07-18 15:34:25 -07003297 if (what & DisplayState::eDisplaySizeChanged) {
3298 if (disp.width != s.width) {
3299 disp.width = s.width;
3300 flags |= eDisplayTransactionNeeded;
3301 }
3302 if (disp.height != s.height) {
3303 disp.height = s.height;
3304 flags |= eDisplayTransactionNeeded;
3305 }
3306 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003307 }
3308 return flags;
3309}
3310
chaviwca27f252018-02-06 16:46:39 -08003311uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3312 const layer_state_t& s = composerState.state;
3313 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3314
Mathias Agopian13127d82013-03-05 17:47:11 -08003315 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003316 if (layer == nullptr) {
3317 return 0;
3318 }
3319
3320 if (layer->isPendingRemoval()) {
3321 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3322 return 0;
3323 }
3324
3325 uint32_t flags = 0;
3326
3327 const uint32_t what = s.what;
3328 bool geometryAppliesWithResize =
3329 what & layer_state_t::eGeometryAppliesWithResize;
3330 if (what & layer_state_t::ePositionChanged) {
3331 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3332 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003333 }
chaviw8b3871a2017-11-01 17:41:01 -07003334 }
3335 if (what & layer_state_t::eLayerChanged) {
3336 // NOTE: index needs to be calculated before we update the state
3337 const auto& p = layer->getParent();
3338 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003339 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003340 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003341 mCurrentState.layersSortedByZ.removeAt(idx);
3342 mCurrentState.layersSortedByZ.add(layer);
3343 // we need traversal (state changed)
3344 // AND transaction (list changed)
3345 flags |= eTransactionNeeded|eTraversalNeeded;
3346 }
chaviw8b3871a2017-11-01 17:41:01 -07003347 } else {
3348 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003349 flags |= eTransactionNeeded|eTraversalNeeded;
3350 }
3351 }
chaviw8b3871a2017-11-01 17:41:01 -07003352 }
3353 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003354 // NOTE: index needs to be calculated before we update the state
3355 const auto& p = layer->getParent();
3356 if (p == nullptr) {
3357 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3358 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3359 mCurrentState.layersSortedByZ.removeAt(idx);
3360 mCurrentState.layersSortedByZ.add(layer);
3361 // we need traversal (state changed)
3362 // AND transaction (list changed)
3363 flags |= eTransactionNeeded|eTraversalNeeded;
3364 }
3365 } else {
3366 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3367 flags |= eTransactionNeeded|eTraversalNeeded;
3368 }
chaviw8b3871a2017-11-01 17:41:01 -07003369 }
3370 }
3371 if (what & layer_state_t::eSizeChanged) {
3372 if (layer->setSize(s.w, s.h)) {
3373 flags |= eTraversalNeeded;
3374 }
3375 }
3376 if (what & layer_state_t::eAlphaChanged) {
3377 if (layer->setAlpha(s.alpha))
3378 flags |= eTraversalNeeded;
3379 }
3380 if (what & layer_state_t::eColorChanged) {
3381 if (layer->setColor(s.color))
3382 flags |= eTraversalNeeded;
3383 }
3384 if (what & layer_state_t::eMatrixChanged) {
3385 if (layer->setMatrix(s.matrix))
3386 flags |= eTraversalNeeded;
3387 }
3388 if (what & layer_state_t::eTransparentRegionChanged) {
3389 if (layer->setTransparentRegionHint(s.transparentRegion))
3390 flags |= eTraversalNeeded;
3391 }
3392 if (what & layer_state_t::eFlagsChanged) {
3393 if (layer->setFlags(s.flags, s.mask))
3394 flags |= eTraversalNeeded;
3395 }
3396 if (what & layer_state_t::eCropChanged) {
3397 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3398 flags |= eTraversalNeeded;
3399 }
3400 if (what & layer_state_t::eFinalCropChanged) {
3401 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3402 flags |= eTraversalNeeded;
3403 }
3404 if (what & layer_state_t::eLayerStackChanged) {
3405 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3406 // We only allow setting layer stacks for top level layers,
3407 // everything else inherits layer stack from its parent.
3408 if (layer->hasParent()) {
3409 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3410 layer->getName().string());
3411 } else if (idx < 0) {
3412 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3413 "that also does not appear in the top level layer list. Something"
3414 " has gone wrong.", layer->getName().string());
3415 } else if (layer->setLayerStack(s.layerStack)) {
3416 mCurrentState.layersSortedByZ.removeAt(idx);
3417 mCurrentState.layersSortedByZ.add(layer);
3418 // we need traversal (state changed)
3419 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003420 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003421 }
3422 }
3423 if (what & layer_state_t::eDeferTransaction) {
3424 if (s.barrierHandle != nullptr) {
3425 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3426 } else if (s.barrierGbp != nullptr) {
3427 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3428 if (authenticateSurfaceTextureLocked(gbp)) {
3429 const auto& otherLayer =
3430 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3431 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3432 } else {
3433 ALOGE("Attempt to defer transaction to to an"
3434 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003435 }
3436 }
chaviw8b3871a2017-11-01 17:41:01 -07003437 // We don't trigger a traversal here because if no other state is
3438 // changed, we don't want this to cause any more work
3439 }
3440 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003441 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003442 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003443 if (!hadParent) {
3444 mCurrentState.layersSortedByZ.remove(layer);
3445 }
chaviw8b3871a2017-11-01 17:41:01 -07003446 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003447 }
chaviw8b3871a2017-11-01 17:41:01 -07003448 }
3449 if (what & layer_state_t::eReparentChildren) {
3450 if (layer->reparentChildren(s.reparentHandle)) {
3451 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003452 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003453 }
chaviw8b3871a2017-11-01 17:41:01 -07003454 if (what & layer_state_t::eDetachChildren) {
3455 layer->detachChildren();
3456 }
3457 if (what & layer_state_t::eOverrideScalingModeChanged) {
3458 layer->setOverrideScalingMode(s.overrideScalingMode);
3459 // We don't trigger a traversal here because if no other state is
3460 // changed, we don't want this to cause any more work
3461 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003462 return flags;
3463}
3464
chaviwca27f252018-02-06 16:46:39 -08003465void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3466 const layer_state_t& state = composerState.state;
3467 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3468
3469 sp<Layer> layer(client->getLayerUser(state.surface));
3470 if (layer == nullptr) {
3471 return;
3472 }
3473
3474 if (layer->isPendingRemoval()) {
3475 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3476 return;
3477 }
3478
3479 if (state.what & layer_state_t::eDestroySurface) {
3480 removeLayerLocked(mStateLock, layer);
3481 }
3482}
3483
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003484status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003485 const String8& name,
3486 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003487 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliuccd34842018-03-14 12:26:23 -07003488 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003489 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003490{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003491 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003492 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003493 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003494 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003495 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003496
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003497 status_t result = NO_ERROR;
3498
3499 sp<Layer> layer;
3500
Cody Northropbc755282017-03-31 12:00:08 -06003501 String8 uniqueName = getUniqueLayerName(name);
3502
Mathias Agopian3165cc22012-08-08 19:42:09 -07003503 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3504 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003505 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003506 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003507 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003508
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003509 break;
chaviw13fdc492017-06-27 12:40:18 -07003510 case ISurfaceComposerClient::eFXSurfaceColor:
3511 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003512 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003513 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003514 break;
3515 default:
3516 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003517 break;
3518 }
3519
Dan Stoza7d89d062015-04-30 13:29:25 -07003520 if (result != NO_ERROR) {
3521 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003522 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003523
Chia-I Wuab0c3192017-08-01 11:29:00 -07003524 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3525 // TODO b/64227542
3526 if (windowType == 441731) {
3527 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3528 layer->setPrimaryDisplayOnly();
3529 }
3530
Albert Chaulk479c60c2017-01-27 14:21:34 -05003531 layer->setInfo(windowType, ownerUid);
3532
Robert Carr1f0a16a2016-10-24 16:27:39 -07003533 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003534 if (result != NO_ERROR) {
3535 return result;
3536 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003537 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003538
3539 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003540 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003541}
3542
Cody Northropbc755282017-03-31 12:00:08 -06003543String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3544{
3545 bool matchFound = true;
3546 uint32_t dupeCounter = 0;
3547
3548 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3549 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3550
3551 // Loop over layers until we're sure there is no matching name
3552 while (matchFound) {
3553 matchFound = false;
3554 mDrawingState.traverseInZOrder([&](Layer* layer) {
3555 if (layer->getName() == uniqueName) {
3556 matchFound = true;
3557 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3558 }
3559 });
3560 }
3561
3562 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3563
3564 return uniqueName;
3565}
3566
David Sodman0c69cad2017-08-21 12:12:51 -07003567status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003568 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3569 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003570{
3571 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003572 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003573 case PIXEL_FORMAT_TRANSPARENT:
3574 case PIXEL_FORMAT_TRANSLUCENT:
3575 format = PIXEL_FORMAT_RGBA_8888;
3576 break;
3577 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003578 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003579 break;
3580 }
3581
David Sodman0c69cad2017-08-21 12:12:51 -07003582 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3583 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003584 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003585 *handle = layer->getHandle();
3586 *gbp = layer->getProducer();
3587 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003588 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003589
David Sodman0c69cad2017-08-21 12:12:51 -07003590 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003591 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003592}
3593
chaviw13fdc492017-06-27 12:40:18 -07003594status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003595 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003596 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003597{
chaviw13fdc492017-06-27 12:40:18 -07003598 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003599 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003600 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003601}
3602
Mathias Agopianac9fa422013-02-11 16:40:36 -08003603status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003604{
Robert Carr9524cb32017-02-13 11:32:32 -08003605 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003606 status_t err = NO_ERROR;
3607 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003608 if (l != nullptr) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003609 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003610 err = removeLayer(l);
3611 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3612 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003613 }
3614 return err;
3615}
3616
Mathias Agopian13127d82013-03-05 17:47:11 -08003617status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003618{
Mathias Agopian67106042013-03-14 19:18:13 -07003619 // called by ~LayerCleaner() when all references to the IBinder (handle)
3620 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003621 sp<Layer> l = layer.promote();
3622 if (l == nullptr) {
3623 // The layer has already been removed, carry on
3624 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003625 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003626 // If we have a parent, then we can continue to live as long as it does.
3627 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003628}
3629
Mathias Agopianb60314a2012-04-10 22:09:54 -07003630// ---------------------------------------------------------------------------
3631
Andy McFadden13a082e2012-08-24 10:16:42 -07003632void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003633 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003634 Vector<ComposerState> state;
3635 Vector<DisplayState> displays;
3636 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003637 d.what = DisplayState::eDisplayProjectionChanged |
3638 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003639 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003640 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003641 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003642 d.frame.makeInvalid();
3643 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003644 d.width = 0;
3645 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003646 displays.add(d);
3647 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003648 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3649 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003650
David Sodman105b7dc2017-11-04 20:28:14 -07003651 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003652 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003653 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003654
Brian Andersond0010582017-03-07 13:20:31 -08003655 // Use phase of 0 since phase is not known.
3656 // Use latency of 0, which will snap to the ideal latency.
3657 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003658}
3659
3660void SurfaceFlinger::initializeDisplays() {
3661 class MessageScreenInitialized : public MessageBase {
3662 SurfaceFlinger* flinger;
3663 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003664 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003665 virtual bool handler() {
3666 flinger->onInitializeDisplays();
3667 return true;
3668 }
3669 };
3670 sp<MessageBase> msg = new MessageScreenInitialized(this);
3671 postMessageAsync(msg); // we may be called from main thread, use async message
3672}
3673
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003674void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003675 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003676 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3677 this);
3678 int32_t type = hw->getDisplayType();
3679 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003680
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003681 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003682 return;
3683 }
3684
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003685 hw->setPowerMode(mode);
3686 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3687 ALOGW("Trying to set power mode for virtual display");
3688 return;
3689 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003690
Lloyd Pique4d234852018-01-22 17:21:36 -08003691 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003692 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003693 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3694 if (idx < 0) {
3695 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3696 return;
3697 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003698 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003699 }
3700
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003701 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003702 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003703 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003704 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3705 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003706 // FIXME: eventthread only knows about the main display right now
3707 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003708 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003709 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003710
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003711 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003712 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003713 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003714
3715 struct sched_param param = {0};
3716 param.sched_priority = 1;
3717 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3718 ALOGW("Couldn't set SCHED_FIFO on display on");
3719 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003720 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003721 // Turn off the display
3722 struct sched_param param = {0};
3723 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3724 ALOGW("Couldn't set SCHED_OTHER on display off");
3725 }
3726
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003727 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3728 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003729 disableHardwareVsync(true); // also cancels any in-progress resync
3730
Mathias Agopiancde87a32012-09-13 14:09:01 -07003731 // FIXME: eventthread only knows about the main display right now
3732 mEventThread->onScreenReleased();
3733 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003734
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003735 getHwComposer().setPowerMode(type, mode);
3736 mVisibleRegionsDirty = true;
3737 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003738 } else if (mode == HWC_POWER_MODE_DOZE ||
3739 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003740 // Update display while dozing
3741 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003742 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3743 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003744 // FIXME: eventthread only knows about the main display right now
3745 mEventThread->onScreenAcquired();
3746 resyncToHardwareVsync(true);
3747 }
3748 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3749 // Leave display going to doze
3750 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3751 disableHardwareVsync(true); // also cancels any in-progress resync
3752 // FIXME: eventthread only knows about the main display right now
3753 mEventThread->onScreenReleased();
3754 }
3755 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003756 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003757 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003758 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003759 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003760 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003761}
3762
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003763void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3764 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003765 SurfaceFlinger& mFlinger;
3766 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003767 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003768 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003769 MessageSetPowerMode(SurfaceFlinger& flinger,
3770 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3771 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003772 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003773 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003774 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003775 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003776 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003777 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003778 ALOGW("Attempt to set power mode = %d for virtual display",
3779 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003780 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003781 mFlinger.setPowerModeInternal(
3782 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003783 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003784 return true;
3785 }
3786 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003787 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003788 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003789}
3790
3791// ---------------------------------------------------------------------------
3792
Lloyd Pique755e3192018-01-31 16:46:15 -08003793status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3794 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003795 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003796
Mathias Agopianbd115332013-04-18 16:41:04 -07003797 IPCThreadState* ipc = IPCThreadState::self();
3798 const int pid = ipc->getCallingPid();
3799 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003800
Mathias Agopianbd115332013-04-18 16:41:04 -07003801 if ((uid != AID_SHELL) &&
3802 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003803 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003804 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003805 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003806 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003807 // (this would indicate SF is stuck, but we want to be able to
3808 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003809 status_t err = mStateLock.timedLock(s2ns(1));
3810 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003811 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003812 result.appendFormat(
3813 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3814 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003815 }
3816
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003817 bool dumpAll = true;
3818 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003819 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003820
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003821 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003822 if ((index < numArgs) &&
3823 (args[index] == String16("--list"))) {
3824 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003825 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003826 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003827 }
3828
3829 if ((index < numArgs) &&
3830 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003831 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003832 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003833 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003834 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003835
3836 if ((index < numArgs) &&
3837 (args[index] == String16("--latency-clear"))) {
3838 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003839 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003840 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003841 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003842
3843 if ((index < numArgs) &&
3844 (args[index] == String16("--dispsync"))) {
3845 index++;
3846 mPrimaryDispSync.dump(result);
3847 dumpAll = false;
3848 }
Dan Stozab90cf072015-03-05 11:05:59 -08003849
3850 if ((index < numArgs) &&
3851 (args[index] == String16("--static-screen"))) {
3852 index++;
3853 dumpStaticScreenStats(result);
3854 dumpAll = false;
3855 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003856
3857 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003858 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003859 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003860 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003861 dumpAll = false;
3862 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003863
3864 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3865 index++;
3866 dumpWideColorInfo(result);
3867 dumpAll = false;
3868 }
Yiwei Zhang068e31b2018-02-21 13:02:45 -08003869
3870 if ((index < numArgs) &&
3871 (args[index] == String16("--enable-layer-stats"))) {
3872 index++;
3873 mLayerStats.enable();
3874 dumpAll = false;
3875 }
3876
3877 if ((index < numArgs) &&
3878 (args[index] == String16("--disable-layer-stats"))) {
3879 index++;
3880 mLayerStats.disable();
3881 dumpAll = false;
3882 }
3883
3884 if ((index < numArgs) &&
3885 (args[index] == String16("--clear-layer-stats"))) {
3886 index++;
3887 mLayerStats.clear();
3888 dumpAll = false;
3889 }
3890
3891 if ((index < numArgs) &&
3892 (args[index] == String16("--dump-layer-stats"))) {
3893 index++;
3894 mLayerStats.dump(result);
3895 dumpAll = false;
3896 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -07003897
3898 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3899 index++;
3900 mTimeStats.parseArgs(asProto, args, index, result);
3901 dumpAll = false;
3902 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003903 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003904
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003905 if (dumpAll) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -07003906 if (asProto) {
3907 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3908 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3909 } else {
3910 dumpAllLocked(args, index, result);
3911 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08003912 }
3913
Mathias Agopian9795c422009-08-26 16:36:26 -07003914 if (locked) {
3915 mStateLock.unlock();
3916 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003917 }
3918 write(fd, result.string(), result.size());
3919 return NO_ERROR;
3920}
3921
Dan Stozac7014012014-02-14 15:03:43 -08003922void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3923 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003924{
Robert Carr2047fae2016-11-28 14:09:09 -08003925 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003926 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003927 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003928}
3929
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003930void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003931 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003932{
3933 String8 name;
3934 if (index < args.size()) {
3935 name = String8(args[index]);
3936 index++;
3937 }
3938
David Sodman105b7dc2017-11-04 20:28:14 -07003939 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003940 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003941 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003942
3943 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003944 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003945 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003946 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003947 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003948 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003949 }
Robert Carr2047fae2016-11-28 14:09:09 -08003950 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003951 }
3952}
3953
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003954void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003955 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003956{
3957 String8 name;
3958 if (index < args.size()) {
3959 name = String8(args[index]);
3960 index++;
3961 }
3962
Robert Carr2047fae2016-11-28 14:09:09 -08003963 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003964 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003965 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003966 }
Robert Carr2047fae2016-11-28 14:09:09 -08003967 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003968
Svetoslavd85084b2014-03-20 10:28:31 -07003969 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003970}
3971
Jamie Gennis6547ff42013-07-16 20:12:42 -07003972// This should only be called from the main thread. Otherwise it would need
3973// the lock and should use mCurrentState rather than mDrawingState.
3974void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003975 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003976 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003977 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003978
3979 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3980}
3981
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003982void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003983{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003984 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003985
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003986 if (isLayerTripleBufferingDisabled())
3987 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003988
3989 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003990 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003991 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003992 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003993 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3994 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003995 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003996}
3997
Dan Stozab90cf072015-03-05 11:05:59 -08003998void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3999{
4000 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004001 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4002 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004003 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004004 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004005 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4006 b + 1, bucketTimeSec, percent);
4007 }
David Sodman4a36e932017-11-07 14:29:47 -08004008 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004009 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004010 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004011 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004012 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004013}
4014
Dan Stozae77c7662016-05-13 11:37:28 -07004015void SurfaceFlinger::recordBufferingStats(const char* layerName,
4016 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004017 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4018 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004019 for (const auto& segment : history) {
4020 if (!segment.usedThirdBuffer) {
4021 stats.twoBufferTime += segment.totalTime;
4022 }
4023 if (segment.occupancyAverage < 1.0f) {
4024 stats.doubleBufferedTime += segment.totalTime;
4025 } else if (segment.occupancyAverage < 2.0f) {
4026 stats.tripleBufferedTime += segment.totalTime;
4027 }
4028 ++stats.numSegments;
4029 stats.totalTime += segment.totalTime;
4030 }
4031}
4032
Brian Andersond6927fb2016-07-23 23:37:30 -07004033void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4034 result.appendFormat("Layer frame timestamps:\n");
4035
4036 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4037 const size_t count = currentLayers.size();
4038 for (size_t i=0 ; i<count ; i++) {
4039 currentLayers[i]->dumpFrameEvents(result);
4040 }
4041}
4042
Dan Stozae77c7662016-05-13 11:37:28 -07004043void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4044 result.append("Buffering stats:\n");
4045 result.append(" [Layer name] <Active time> <Two buffer> "
4046 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004047 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004048 typedef std::tuple<std::string, float, float, float> BufferTuple;
4049 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004050 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004051 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004052 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004053 if (stats.numSegments == 0) {
4054 continue;
4055 }
4056 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4057 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4058 stats.totalTime;
4059 float doubleBufferRatio = static_cast<float>(
4060 stats.doubleBufferedTime) / stats.totalTime;
4061 float tripleBufferRatio = static_cast<float>(
4062 stats.tripleBufferedTime) / stats.totalTime;
4063 sorted.insert({activeTime, {name, twoBufferRatio,
4064 doubleBufferRatio, tripleBufferRatio}});
4065 }
4066 for (const auto& sortedPair : sorted) {
4067 float activeTime = sortedPair.first;
4068 const BufferTuple& values = sortedPair.second;
4069 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4070 std::get<0>(values).c_str(), activeTime,
4071 std::get<1>(values), std::get<2>(values),
4072 std::get<3>(values));
4073 }
4074 result.append("\n");
4075}
4076
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004077void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4078 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004079 result.appendFormat("DisplayColorSetting: %d\n", mDisplayColorSetting);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004080
4081 // TODO: print out if wide-color mode is active or not
4082
4083 for (size_t d = 0; d < mDisplays.size(); d++) {
4084 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4085 int32_t hwcId = displayDevice->getHwcDisplayId();
4086 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4087 continue;
4088 }
4089
4090 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004091 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004092 for (auto&& mode : modes) {
4093 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4094 }
4095
Peiyong Lina52f0292018-03-14 17:26:31 -07004096 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004097 result.appendFormat(" Current color mode: %s (%d)\n",
4098 decodeColorMode(currentMode).c_str(), currentMode);
4099 }
4100 result.append("\n");
4101}
4102
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004103LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004104 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004105 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4106 const State& state = useDrawing ? mDrawingState : mCurrentState;
4107 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004108 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004109 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004110 });
4111
4112 return layersProto;
4113}
4114
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004115LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4116 LayersProto layersProto;
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004117 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004118
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004119 SizeProto* resolution = layersProto.mutable_resolution();
4120 resolution->set_w(displayDevice->getWidth());
4121 resolution->set_h(displayDevice->getHeight());
4122
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004123 layersProto.set_color_mode(decodeColorMode(displayDevice->getActiveColorMode()));
4124 layersProto.set_color_transform(decodeColorTransform(displayDevice->getColorTransform()));
4125 layersProto.set_global_transform(
4126 static_cast<int32_t>(displayDevice->getOrientationTransform()));
4127
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004128 mDrawingState.traverseInZOrder([&](Layer* layer) {
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004129 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004130 LayerProto* layerProto = layersProto.add_layers();
4131 layer->writeToProto(layerProto, hwcId);
4132 }
4133 });
4134
4135 return layersProto;
4136}
4137
Mathias Agopian74d211a2013-04-22 16:55:35 +02004138void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4139 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004140{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004141 bool colorize = false;
4142 if (index < args.size()
4143 && (args[index] == String16("--color"))) {
4144 colorize = true;
4145 index++;
4146 }
4147
4148 Colorizer colorizer(colorize);
4149
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004150 // figure out if we're stuck somewhere
4151 const nsecs_t now = systemTime();
4152 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4153 const nsecs_t inTransaction(mDebugInTransaction);
4154 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4155 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4156
4157 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004158 * Dump library configuration.
4159 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004160
4161 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004162 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004163 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004164 appendSfConfigString(result);
4165 appendUiConfigString(result);
4166 appendGuiConfigString(result);
4167 result.append("\n");
4168
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004169 result.append("\nWide-Color information:\n");
4170 dumpWideColorInfo(result);
4171
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004172 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004173 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004174 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004175 result.append(SyncFeatures::getInstance().toString());
4176 result.append("\n");
4177
David Sodman105b7dc2017-11-04 20:28:14 -07004178 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004179
Andy McFadden41d67d72014-04-25 16:58:34 -07004180 colorizer.bold(result);
4181 result.append("DispSync configuration: ");
4182 colorizer.reset(result);
Dan Stoza2713c302018-03-28 17:07:36 -07004183 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, early sf phase %" PRId64
4184 " ns, present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4185 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, mVsyncModulator.getEarlyPhaseOffset(),
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004186 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004187 result.append("\n");
4188
Dan Stozab90cf072015-03-05 11:05:59 -08004189 // Dump static screen stats
4190 result.append("\n");
4191 dumpStaticScreenStats(result);
4192 result.append("\n");
4193
Dan Stozae77c7662016-05-13 11:37:28 -07004194 dumpBufferingStats(result);
4195
Andy McFadden4803b742012-09-24 19:07:20 -07004196 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004197 * Dump the visible layer list
4198 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004199 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004200 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004201 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4202 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004203 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004204
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004205 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004206 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7794ec12018-03-14 13:28:39 -07004207 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004208 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004209
4210 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004211 * Dump Display state
4212 */
4213
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004214 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004215 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004216 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004217 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4218 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004219 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004220 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004221 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004222
4223 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004224 * Dump SurfaceFlinger global state
4225 */
4226
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004227 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004228 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004229 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004230
Mathias Agopian888c8222012-08-04 21:10:38 -07004231 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004232 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004233
David Sodmanbc815282017-11-05 18:57:52 -08004234 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004235
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004236 if (hw) {
4237 hw->undefinedRegion.dump(result, "undefinedRegion");
4238 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4239 hw->getOrientation(), hw->isDisplayOn());
4240 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004241 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004242 " last eglSwapBuffers() time: %f us\n"
4243 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004244 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004245 " refresh-rate : %f fps\n"
4246 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004247 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004248 " gpu_to_cpu_unsupported : %d\n"
4249 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004250 mLastSwapBufferTime/1000.0,
4251 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004252 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004253 1e9 / activeConfig->getVsyncPeriod(),
4254 activeConfig->getDpiX(),
4255 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004256 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004257
Mathias Agopian74d211a2013-04-22 16:55:35 +02004258 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004259 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004260
Mathias Agopian74d211a2013-04-22 16:55:35 +02004261 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004262 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004263
4264 /*
4265 * VSYNC state
4266 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004267 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004268 result.append("\n");
4269
4270 /*
4271 * HWC layer minidump
4272 */
4273 for (size_t d = 0; d < mDisplays.size(); d++) {
4274 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4275 int32_t hwcId = displayDevice->getHwcDisplayId();
4276 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4277 continue;
4278 }
4279
4280 result.appendFormat("Display %d HWC layers:\n", hwcId);
4281 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004282 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004283 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004284 });
Dan Stozae22aec72016-08-01 13:20:59 -07004285 result.append("\n");
4286 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004287
4288 /*
4289 * Dump HWComposer state
4290 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004291 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004292 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004293 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004294 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004295 result.appendFormat(" h/w composer %s\n",
4296 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004297 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004298
4299 /*
4300 * Dump gralloc state
4301 */
4302 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4303 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004304
4305 /*
4306 * Dump VrFlinger state if in use.
4307 */
4308 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4309 result.append("VrFlinger state:\n");
4310 result.append(mVrFlinger->Dump().c_str());
4311 result.append("\n");
4312 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004313}
4314
Mathias Agopian13127d82013-03-05 17:47:11 -08004315const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004316SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004317 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004318 wp<IBinder> dpy;
4319 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4320 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4321 dpy = mDisplays.keyAt(i);
4322 break;
4323 }
4324 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004325 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004326 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4327 // Just use the primary display so we have something to return
4328 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4329 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004330 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004331}
4332
Keun young Park63f165f2012-08-31 10:53:36 -07004333bool SurfaceFlinger::startDdmConnection()
4334{
4335 void* libddmconnection_dso =
4336 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4337 if (!libddmconnection_dso) {
4338 return false;
4339 }
4340 void (*DdmConnection_start)(const char* name);
4341 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004342 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004343 if (!DdmConnection_start) {
4344 dlclose(libddmconnection_dso);
4345 return false;
4346 }
4347 (*DdmConnection_start)(getServiceName());
4348 return true;
4349}
4350
Chia-I Wu28f320b2018-05-03 11:02:56 -07004351void SurfaceFlinger::updateColorMatrixLocked() {
4352 mat4 colorMatrix;
4353 if (mGlobalSaturationFactor != 1.0f) {
4354 // Rec.709 luma coefficients
4355 float3 luminance{0.213f, 0.715f, 0.072f};
4356 luminance *= 1.0f - mGlobalSaturationFactor;
4357 mat4 saturationMatrix = mat4(
4358 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4359 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4360 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4361 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4362 );
4363 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4364 } else {
4365 colorMatrix = mClientColorMatrix * mDaltonizer();
4366 }
4367
4368 if (mCurrentState.colorMatrix != colorMatrix) {
4369 mCurrentState.colorMatrix = colorMatrix;
4370 mCurrentState.colorMatrixChanged = true;
4371 setTransactionFlags(eTransactionNeeded);
4372 }
4373}
4374
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004375status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004376 switch (code) {
4377 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004378 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004379 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004380 case CLEAR_ANIMATION_FRAME_STATS:
4381 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004382 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004383 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004384 case ENABLE_VSYNC_INJECTIONS:
4385 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004386 {
4387 // codes that require permission check
4388 IPCThreadState* ipc = IPCThreadState::self();
4389 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004390 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004391 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004392 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004393 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004394 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004395 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004396 break;
4397 }
Robert Carr1db73f62016-12-21 12:58:51 -08004398 /*
4399 * Calling setTransactionState is safe, because you need to have been
4400 * granted a reference to Client* and Handle* to do anything with it.
4401 *
4402 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4403 */
4404 case SET_TRANSACTION_STATE:
4405 case CREATE_SCOPED_CONNECTION:
4406 {
4407 return OK;
4408 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004409 case CAPTURE_SCREEN:
4410 {
4411 // codes that require permission check
4412 IPCThreadState* ipc = IPCThreadState::self();
4413 const int pid = ipc->getCallingPid();
4414 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004415 if ((uid != AID_GRAPHICS) &&
4416 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004417 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004418 return PERMISSION_DENIED;
4419 }
4420 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004421 }
chaviwa76b2712017-09-20 12:02:26 -07004422 case CAPTURE_LAYERS: {
4423 IPCThreadState* ipc = IPCThreadState::self();
4424 const int pid = ipc->getCallingPid();
4425 const int uid = ipc->getCallingUid();
4426 if ((uid != AID_GRAPHICS) &&
4427 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4428 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4429 return PERMISSION_DENIED;
4430 }
4431 break;
4432 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004433 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004434 return OK;
4435}
4436
4437status_t SurfaceFlinger::onTransact(
4438 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4439{
4440 status_t credentialCheck = CheckTransactCodeCredentials(code);
4441 if (credentialCheck != OK) {
4442 return credentialCheck;
4443 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004444
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004445 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4446 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004447 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004448 IPCThreadState* ipc = IPCThreadState::self();
4449 const int uid = ipc->getCallingUid();
4450 if (CC_UNLIKELY(uid != AID_SYSTEM
4451 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004452 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004453 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004454 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004455 return PERMISSION_DENIED;
4456 }
4457 int n;
4458 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004459 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004460 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004461 return NO_ERROR;
4462 case 1002: // SHOW_UPDATES
4463 n = data.readInt32();
4464 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004465 invalidateHwcGeometry();
4466 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004467 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004468 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004469 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004470 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004471 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004472 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004473 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004474 setTransactionFlags(
4475 eTransactionNeeded|
4476 eDisplayTransactionNeeded|
4477 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004478 return NO_ERROR;
4479 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004480 case 1006:{ // send empty update
4481 signalRefresh();
4482 return NO_ERROR;
4483 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004484 case 1008: // toggle use of hw composer
4485 n = data.readInt32();
4486 mDebugDisableHWC = n ? 1 : 0;
4487 invalidateHwcGeometry();
4488 repaintEverything();
4489 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004490 case 1009: // toggle use of transform hint
4491 n = data.readInt32();
4492 mDebugDisableTransformHint = n ? 1 : 0;
4493 invalidateHwcGeometry();
4494 repaintEverything();
4495 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004496 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004497 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004498 reply->writeInt32(0);
4499 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004500 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004501 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004502 return NO_ERROR;
4503 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004504 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004505 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004506 return NO_ERROR;
4507 }
4508 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004509 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004510 // daltonize
4511 n = data.readInt32();
4512 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004513 case 1:
4514 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4515 break;
4516 case 2:
4517 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4518 break;
4519 case 3:
4520 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4521 break;
4522 default:
4523 mDaltonizer.setType(ColorBlindnessType::None);
4524 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004525 }
4526 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004527 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004528 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004529 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004530 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004531
4532 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004533 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004534 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004535 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004536 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004537 // apply a color matrix
4538 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004539 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004540 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004541 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004542 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004543 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004544 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004545 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004546 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004547 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004548 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004549
4550 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4551 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004552 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004553 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4554 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4555 }
4556
Chia-I Wu28f320b2018-05-03 11:02:56 -07004557 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004558 return NO_ERROR;
4559 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004560 // This is an experimental interface
4561 // Needs to be shifted to proper binder interface when we productize
4562 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004563 n = data.readInt32();
4564 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004565 return NO_ERROR;
4566 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004567 case 1017: {
4568 n = data.readInt32();
4569 mForceFullDamage = static_cast<bool>(n);
4570 return NO_ERROR;
4571 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004572 case 1018: { // Modify Choreographer's phase offset
4573 n = data.readInt32();
4574 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4575 return NO_ERROR;
4576 }
4577 case 1019: { // Modify SurfaceFlinger's phase offset
4578 n = data.readInt32();
4579 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4580 return NO_ERROR;
4581 }
Irvel468051e2016-06-13 16:44:44 -07004582 case 1020: { // Layer updates interceptor
4583 n = data.readInt32();
4584 if (n) {
4585 ALOGV("Interceptor enabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004586 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004587 }
4588 else{
4589 ALOGV("Interceptor disabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004590 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004591 }
4592 return NO_ERROR;
4593 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004594 case 1021: { // Disable HWC virtual displays
4595 n = data.readInt32();
4596 mUseHwcVirtualDisplays = !n;
4597 return NO_ERROR;
4598 }
Romain Guy0147a172017-06-01 13:53:56 -07004599 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004600 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004601 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004602
Chia-I Wu28f320b2018-05-03 11:02:56 -07004603 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004604 return NO_ERROR;
4605 }
Romain Guy54f154a2017-10-24 21:40:32 +01004606 case 1023: { // Set native mode
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004607 int32_t value = data.readInt32();
4608 if (value > 2) {
4609 return BAD_VALUE;
4610 }
4611 if (value == 2 && !mBuiltinDisplaySupportsEnhance) {
4612 return BAD_VALUE;
4613 }
Romain Guy54f154a2017-10-24 21:40:32 +01004614
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004615 mDisplayColorSetting = toDisplayColorSetting(value);
Romain Guy54f154a2017-10-24 21:40:32 +01004616 invalidateHwcGeometry();
4617 repaintEverything();
4618 return NO_ERROR;
4619 }
4620 case 1024: { // Is wide color gamut rendering/color management supported?
4621 reply->writeBool(hasWideColorDisplay);
4622 return NO_ERROR;
4623 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004624 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004625 n = data.readInt32();
4626 if (n) {
4627 ALOGV("LayerTracing enabled");
4628 mTracing.enable();
4629 doTracing("tracing.enable");
4630 reply->writeInt32(NO_ERROR);
4631 } else {
4632 ALOGV("LayerTracing disabled");
4633 status_t err = mTracing.disable();
4634 reply->writeInt32(err);
4635 }
4636 return NO_ERROR;
4637 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004638 case 1026: { // Get layer tracing status
4639 reply->writeBool(mTracing.isEnabled());
4640 return NO_ERROR;
4641 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004642 // Is a DisplayColorSetting supported?
4643 case 1027: {
4644 int32_t value = data.readInt32();
4645 switch (value) {
4646 case 0:
4647 reply->writeBool(hasWideColorDisplay);
4648 return NO_ERROR;
4649 case 1:
4650 reply->writeBool(true);
4651 return NO_ERROR;
4652 case 2:
4653 reply->writeBool(mBuiltinDisplaySupportsEnhance);
4654 return NO_ERROR;
4655 default:
4656 return BAD_VALUE;
4657 }
4658 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004659 }
4660 }
4661 return err;
4662}
4663
Steven Thomas6d8110b2017-08-31 18:24:21 -07004664void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004665 android_atomic_or(1, &mRepaintEverything);
4666 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004667}
4668
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004669// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4670class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004671public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004672 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4673 ~WindowDisconnector() {
4674 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004675 }
4676
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004677private:
4678 ANativeWindow* mWindow;
4679 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004680};
4681
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004682status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4683 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4684 int32_t minLayerZ, int32_t maxLayerZ,
4685 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004686 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004687 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004688
chaviwa76b2712017-09-20 12:02:26 -07004689 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4690
4691 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004692 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4693
chaviwa76b2712017-09-20 12:02:26 -07004694 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4695
4696 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4697 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004698 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004699}
4700
4701status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004702 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004703 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004704 ATRACE_CALL();
4705
4706 class LayerRenderArea : public RenderArea {
4707 public:
Robert Carr578038f2018-03-09 12:25:24 -08004708 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4709 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004710 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004711 mLayer(layer),
4712 mCrop(crop),
4713 mFlinger(flinger),
4714 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004715 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004716 Rect getBounds() const override {
4717 const Layer::State& layerState(mLayer->getDrawingState());
4718 return Rect(layerState.active.w, layerState.active.h);
4719 }
4720 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4721 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4722 bool isSecure() const override { return false; }
4723 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004724 Rect getSourceCrop() const override {
4725 if (mCrop.isEmpty()) {
4726 return getBounds();
4727 } else {
4728 return mCrop;
4729 }
4730 }
4731 bool getWideColorSupport() const override { return false; }
4732 Dataspace getDataSpace() const override { return Dataspace::UNKNOWN; }
Peiyong Linfb069302018-04-25 14:34:31 -07004733 float getDisplayMaxLuminance() const override {
4734 return DisplayDevice::sDefaultMaxLumiance;
4735 }
Robert Carr578038f2018-03-09 12:25:24 -08004736
4737 class ReparentForDrawing {
4738 public:
4739 const sp<Layer>& oldParent;
4740 const sp<Layer>& newParent;
4741
4742 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4743 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004744 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004745 }
Robert Carr15eae092018-03-23 13:43:53 -07004746 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004747 };
4748
4749 void render(std::function<void()> drawLayers) override {
4750 if (!mChildrenOnly) {
4751 mTransform = mLayer->getTransform().inverse();
4752 drawLayers();
4753 } else {
4754 Rect bounds = getBounds();
4755 screenshotParentLayer =
4756 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4757 bounds.getWidth(), bounds.getHeight(), 0);
4758
4759 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4760 drawLayers();
4761 }
4762 }
chaviwa76b2712017-09-20 12:02:26 -07004763
chaviwa76b2712017-09-20 12:02:26 -07004764 private:
chaviw7206d492017-11-10 16:16:12 -08004765 const sp<Layer> mLayer;
4766 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004767
4768 // In the "childrenOnly" case we reparent the children to a screenshot
4769 // layer which has no properties set and which does not draw.
4770 sp<ContainerLayer> screenshotParentLayer;
4771 Transform mTransform;
4772
4773 SurfaceFlinger* mFlinger;
4774 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004775 };
4776
4777 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4778 auto parent = layerHandle->owner.promote();
4779
chaviw7206d492017-11-10 16:16:12 -08004780 if (parent == nullptr || parent->isPendingRemoval()) {
4781 ALOGE("captureLayers called with a removed parent");
4782 return NAME_NOT_FOUND;
4783 }
4784
Robert Carr578038f2018-03-09 12:25:24 -08004785 const int uid = IPCThreadState::self()->getCallingUid();
4786 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4787 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4788 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4789 return PERMISSION_DENIED;
4790 }
4791
chaviw7206d492017-11-10 16:16:12 -08004792 Rect crop(sourceCrop);
4793 if (sourceCrop.width() <= 0) {
4794 crop.left = 0;
4795 crop.right = parent->getCurrentState().active.w;
4796 }
4797
4798 if (sourceCrop.height() <= 0) {
4799 crop.top = 0;
4800 crop.bottom = parent->getCurrentState().active.h;
4801 }
4802
4803 int32_t reqWidth = crop.width() * frameScale;
4804 int32_t reqHeight = crop.height() * frameScale;
4805
Robert Carr578038f2018-03-09 12:25:24 -08004806 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004807
Robert Carr578038f2018-03-09 12:25:24 -08004808 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004809 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4810 if (!layer->isVisible()) {
4811 return;
Robert Carr578038f2018-03-09 12:25:24 -08004812 } else if (childrenOnly && layer == parent.get()) {
4813 return;
chaviwa76b2712017-09-20 12:02:26 -07004814 }
4815 visitor(layer);
4816 });
4817 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004818 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004819}
4820
4821status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4822 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004823 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004824 bool useIdentityTransform) {
4825 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004826
chaviwa76b2712017-09-20 12:02:26 -07004827 renderArea.updateDimensions();
4828
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004829 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4830 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4831 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4832 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004833
4834 // This mutex protects syncFd and captureResult for communication of the return values from the
4835 // main thread back to this Binder thread
4836 std::mutex captureMutex;
4837 std::condition_variable captureCondition;
4838 std::unique_lock<std::mutex> captureLock(captureMutex);
4839 int syncFd = -1;
4840 std::optional<status_t> captureResult;
4841
Robert Carr03480e22018-01-04 16:02:06 -08004842 const int uid = IPCThreadState::self()->getCallingUid();
4843 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4844
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004845 sp<LambdaMessage> message = new LambdaMessage([&]() {
4846 // If there is a refresh pending, bug out early and tell the binder thread to try again
4847 // after the refresh.
4848 if (mRefreshPending) {
4849 ATRACE_NAME("Skipping screenshot for now");
4850 std::unique_lock<std::mutex> captureLock(captureMutex);
4851 captureResult = std::make_optional<status_t>(EAGAIN);
4852 captureCondition.notify_one();
4853 return;
4854 }
4855
4856 status_t result = NO_ERROR;
4857 int fd = -1;
4858 {
4859 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004860 renderArea.render([&]() {
4861 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4862 useIdentityTransform, forSystem, &fd);
4863 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004864 }
4865
4866 {
4867 std::unique_lock<std::mutex> captureLock(captureMutex);
4868 syncFd = fd;
4869 captureResult = std::make_optional<status_t>(result);
4870 captureCondition.notify_one();
4871 }
4872 });
4873
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004874 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004875 if (result == NO_ERROR) {
4876 captureCondition.wait(captureLock, [&]() { return captureResult; });
4877 while (*captureResult == EAGAIN) {
4878 captureResult.reset();
4879 result = postMessageAsync(message);
4880 if (result != NO_ERROR) {
4881 return result;
4882 }
4883 captureCondition.wait(captureLock, [&]() { return captureResult; });
4884 }
4885 result = *captureResult;
4886 }
4887
4888 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004889 sync_wait(syncFd, -1);
4890 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004891 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004892
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004893 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004894}
4895
chaviwa76b2712017-09-20 12:02:26 -07004896void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4897 TraverseLayersFunction traverseLayers, bool yswap,
4898 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004899 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004900
Lloyd Pique144e1162017-12-20 16:44:52 -08004901 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004902
4903 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004904 const auto raWidth = renderArea.getWidth();
4905 const auto raHeight = renderArea.getHeight();
4906
4907 const auto reqWidth = renderArea.getReqWidth();
4908 const auto reqHeight = renderArea.getReqHeight();
4909 Rect sourceCrop = renderArea.getSourceCrop();
4910
4911 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4912 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004913
Dan Stozac1879002014-05-22 15:59:05 -07004914 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004915 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004916 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004917 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004918 }
4919
4920 // ensure that sourceCrop is inside screen
4921 if (sourceCrop.left < 0) {
4922 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4923 }
chaviwa76b2712017-09-20 12:02:26 -07004924 if (sourceCrop.right > raWidth) {
4925 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004926 }
4927 if (sourceCrop.top < 0) {
4928 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4929 }
chaviwa76b2712017-09-20 12:02:26 -07004930 if (sourceCrop.bottom > raHeight) {
4931 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004932 }
4933
Peiyong Lin34beb7a2018-03-28 11:57:12 -07004934 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004935 if (renderArea.getWideColorSupport()) {
4936 outputDataspace = renderArea.getDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004937 }
Peiyong Linfb069302018-04-25 14:34:31 -07004938 engine.setOutputDataSpace(outputDataspace);
4939 engine.setDisplayMaxLuminance(renderArea.getDisplayMaxLuminance());
Romain Guy88d37dd2017-05-26 17:57:05 -07004940
Mathias Agopian180f10d2013-04-10 22:55:41 -07004941 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004942 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004943
4944 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004945 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4946 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004947 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004948
chaviw50da5042018-04-09 13:49:37 -07004949 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004950 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07004951 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004952
chaviwa76b2712017-09-20 12:02:26 -07004953 traverseLayers([&](Layer* layer) {
4954 if (filtering) layer->setFiltering(true);
4955 layer->draw(renderArea, useIdentityTransform);
4956 if (filtering) layer->setFiltering(false);
4957 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004958}
4959
chaviwa76b2712017-09-20 12:02:26 -07004960status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4961 TraverseLayersFunction traverseLayers,
4962 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004963 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08004964 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07004965 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004966 ATRACE_CALL();
4967
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004968 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004969
4970 traverseLayers([&](Layer* layer) {
4971 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4972 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004973
Robert Carr03480e22018-01-04 16:02:06 -08004974 // We allow the system server to take screenshots of secure layers for
4975 // use in situations like the Screen-rotation animation and place
4976 // the impetus on WindowManager to not persist them.
4977 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004978 ALOGW("FB is protected: PERMISSION_DENIED");
4979 return PERMISSION_DENIED;
4980 }
4981
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004982 // this binds the given EGLImage as a framebuffer for the
4983 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08004984 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08004985 if (bufferBond.getStatus() != NO_ERROR) {
4986 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004987 return INVALID_OPERATION;
4988 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004989
Dan Stozaabcda352017-06-01 14:37:39 -07004990 // this will in fact render into our dequeued buffer
4991 // via an FBO, which means we didn't have to create
4992 // an EGLSurface and therefore we're not
4993 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004994 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004995
Dan Stozaabcda352017-06-01 14:37:39 -07004996 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08004997 getRenderEngine().finish();
4998 *outSyncFd = -1;
4999
chaviwa76b2712017-09-20 12:02:26 -07005000 const auto reqWidth = renderArea.getReqWidth();
5001 const auto reqHeight = renderArea.getReqHeight();
5002
Dan Stozaabcda352017-06-01 14:37:39 -07005003 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5004 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005005 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005006 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005007 } else {
5008 base::unique_fd syncFd = getRenderEngine().flush();
5009 if (syncFd < 0) {
5010 getRenderEngine().finish();
5011 }
5012 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005013 }
5014
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005015 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005016}
5017
Mathias Agopiand5556842013-09-19 17:08:37 -07005018void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005019 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005020 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005021 for (size_t y = 0; y < h; y++) {
5022 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5023 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005024 if (p[x] != 0xFF000000) return;
5025 }
5026 }
chaviwa76b2712017-09-20 12:02:26 -07005027 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005028
Robert Carr2047fae2016-11-28 14:09:09 -08005029 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005030 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005031 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005032 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5033 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5034 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5035 static_cast<float>(state.color.a));
5036 i++;
5037 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005038 }
5039}
5040
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005041// ---------------------------------------------------------------------------
5042
Dan Stoza412903f2017-04-27 13:42:17 -07005043void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5044 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005045}
5046
Dan Stoza412903f2017-04-27 13:42:17 -07005047void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5048 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005049}
5050
chaviwa76b2712017-09-20 12:02:26 -07005051void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
5052 int32_t maxLayerZ,
5053 const LayerVector::Visitor& visitor) {
5054 // We loop through the first level of layers without traversing,
5055 // as we need to interpret min/max layer Z in the top level Z space.
5056 for (const auto& layer : mDrawingState.layersSortedByZ) {
5057 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5058 continue;
5059 }
5060 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005061 // relative layers are traversed in Layer::traverseInZOrder
5062 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005063 continue;
5064 }
5065 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005066 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5067 return;
5068 }
chaviwa76b2712017-09-20 12:02:26 -07005069 if (!layer->isVisible()) {
5070 return;
5071 }
5072 visitor(layer);
5073 });
5074 }
5075}
5076
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005077}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005078
5079
5080#if defined(__gl_h_)
5081#error "don't include gl/gl.h in this file"
5082#endif
5083
5084#if defined(__gl2_h_)
5085#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005086#endif