blob: 9117207544a5c1f10004418a05d76aa49e5de72f [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
Yiwei Zhang243b3782018-05-15 17:40:04 -0700319 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700320 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
321 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
322
Dan Stoza2713c302018-03-28 17:07:36 -0700323 property_get("debug.sf.early_phase_offset_ns", value, "0");
324 const int earlyWakeupOffsetOffsetNs = atoi(value);
325 ALOGI_IF(earlyWakeupOffsetOffsetNs != 0, "Enabling separate early offset");
326 mVsyncModulator.setPhaseOffsets(sfVsyncPhaseOffsetNs - earlyWakeupOffsetOffsetNs,
327 sfVsyncPhaseOffsetNs);
328
Romain Guy11d63f42017-07-20 12:47:14 -0700329 // We should be reading 'persist.sys.sf.color_saturation' here
330 // but since /data may be encrypted, we need to wait until after vold
331 // comes online to attempt to read the property. The property is
332 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800333
334 if (useTrebleTestingOverride()) {
335 // Without the override SurfaceFlinger cannot connect to HIDL
336 // services that are not listed in the manifests. Considered
337 // deriving the setting from the set service name, but it
338 // would be brittle if the name that's not 'default' is used
339 // for production purposes later on.
340 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
341 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800342}
343
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800344void SurfaceFlinger::onFirstRef()
345{
Lloyd Pique9123ae52018-01-22 17:14:00 -0800346 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800347}
348
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800349SurfaceFlinger::~SurfaceFlinger()
350{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800351}
352
Dan Stozac7014012014-02-14 15:03:43 -0800353void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800354{
355 // the window manager died on us. prepare its eulogy.
356
Andy McFadden13a082e2012-08-24 10:16:42 -0700357 // restore initial conditions (default device unblank, etc)
358 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800359
360 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700361 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800362}
363
Robert Carr1db73f62016-12-21 12:58:51 -0800364static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700365 status_t err = client->initCheck();
366 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800367 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800368 }
Robert Carr1db73f62016-12-21 12:58:51 -0800369 return nullptr;
370}
371
372sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
373 return initClient(new Client(this));
374}
375
376sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
377 const sp<IGraphicBufferProducer>& gbp) {
378 if (authenticateSurfaceTexture(gbp) == false) {
379 return nullptr;
380 }
381 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
382 if (layer == nullptr) {
383 return nullptr;
384 }
385
386 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800387}
388
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700389sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
390 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700391{
392 class DisplayToken : public BBinder {
393 sp<SurfaceFlinger> flinger;
394 virtual ~DisplayToken() {
395 // no more references, this display must be terminated
396 Mutex::Autolock _l(flinger->mStateLock);
397 flinger->mCurrentState.displays.removeItem(this);
398 flinger->setTransactionFlags(eDisplayTransactionNeeded);
399 }
400 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700401 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700402 : flinger(flinger) {
403 }
404 };
405
406 sp<BBinder> token = new DisplayToken(this);
407
408 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700409 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700410 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700411 mCurrentState.displays.add(token, info);
Lloyd Pique4d234852018-01-22 17:21:36 -0800412 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700413 return token;
414}
415
Jesse Hall6c913be2013-08-08 12:15:49 -0700416void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
417 Mutex::Autolock _l(mStateLock);
418
419 ssize_t idx = mCurrentState.displays.indexOfKey(display);
420 if (idx < 0) {
421 ALOGW("destroyDisplay: invalid display token");
422 return;
423 }
424
425 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
426 if (!info.isVirtualDisplay()) {
427 ALOGE("destroyDisplay called for non-virtual display");
428 return;
429 }
Lloyd Pique4d234852018-01-22 17:21:36 -0800430 mInterceptor->saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700431 mCurrentState.displays.removeItemsAt(idx);
432 setTransactionFlags(eDisplayTransactionNeeded);
433}
434
Mathias Agopiane57f2922012-08-09 16:29:12 -0700435sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700436 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700437 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800438 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700439 }
Jesse Hall692c7232012-11-08 15:41:56 -0800440 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700441}
442
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800443void SurfaceFlinger::bootFinished()
444{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700445 if (mStartPropertySetThread->join() != NO_ERROR) {
446 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800447 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800448 const nsecs_t now = systemTime();
449 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000450 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700451
452 // wait patiently for the window manager death
453 const String16 name("window");
454 sp<IBinder> window(defaultServiceManager()->getService(name));
455 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700456 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700457 }
458
Steven Thomas050b2c82017-03-06 11:45:16 -0800459 if (mVrFlinger) {
460 mVrFlinger->OnBootFinished();
461 }
462
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700463 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700464 // formerly we would just kill the process, but we now ask it to exit so it
465 // can choose where to stop the animation.
466 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700467
468 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
469 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
470 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700471
Thierry Strudel2924d012017-08-14 15:19:37 -0700472 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700473 readPersistentProperties();
474 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700475 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800476}
477
Mathias Agopian3f844832013-08-07 21:24:32 -0700478void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700479 class MessageDestroyGLTexture : public MessageBase {
Lloyd Pique144e1162017-12-20 16:44:52 -0800480 RE::RenderEngine& engine;
Mathias Agopian3f844832013-08-07 21:24:32 -0700481 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700482 public:
Lloyd Pique144e1162017-12-20 16:44:52 -0800483 MessageDestroyGLTexture(RE::RenderEngine& engine, uint32_t texture)
484 : engine(engine), texture(texture) {}
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700485 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700486 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700487 return true;
488 }
489 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700490 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700491}
492
Lloyd Piquee83f9312018-02-01 12:53:17 -0800493class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700494public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700495 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000496 const char* name) :
497 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700498 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700499 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000500 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
501 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700502 mDispSync(dispSync),
503 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700504 mVsyncMutex(),
505 mPhaseOffset(phaseOffset),
506 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700507
Lloyd Piquee83f9312018-02-01 12:53:17 -0800508 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700509
Lloyd Piquee83f9312018-02-01 12:53:17 -0800510 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700511 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700512 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000513 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700514 static_cast<DispSync::Callback*>(this));
515 if (err != NO_ERROR) {
516 ALOGE("error registering vsync callback: %s (%d)",
517 strerror(-err), err);
518 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700519 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700520 } else {
521 status_t err = mDispSync->removeEventListener(
522 static_cast<DispSync::Callback*>(this));
523 if (err != NO_ERROR) {
524 ALOGE("error unregistering vsync callback: %s (%d)",
525 strerror(-err), err);
526 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700527 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700528 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700529 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700530 }
531
Lloyd Piquee83f9312018-02-01 12:53:17 -0800532 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700533 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700534 mCallback = callback;
535 }
536
Lloyd Piquee83f9312018-02-01 12:53:17 -0800537 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700538 Mutex::Autolock lock(mVsyncMutex);
539
540 // Normalize phaseOffset to [0, period)
541 auto period = mDispSync->getPeriod();
542 phaseOffset %= period;
543 if (phaseOffset < 0) {
544 // If we're here, then phaseOffset is in (-period, 0). After this
545 // operation, it will be in (0, period)
546 phaseOffset += period;
547 }
548 mPhaseOffset = phaseOffset;
549
550 // If we're not enabled, we don't need to mess with the listeners
551 if (!mEnabled) {
552 return;
553 }
554
Dan Stoza2713c302018-03-28 17:07:36 -0700555 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
556 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700557 if (err != NO_ERROR) {
Dan Stoza2713c302018-03-28 17:07:36 -0700558 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700559 strerror(-err), err);
560 }
561 }
562
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700563private:
564 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800565 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700566 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700567 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700568 callback = mCallback;
569
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700570 if (mTraceVsync) {
571 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700572 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700573 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700574 }
575
Peiyong Lin566a3b42018-01-09 18:22:43 -0800576 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700577 callback->onVSyncEvent(when);
578 }
579 }
580
Tim Murray4a4e4a22016-04-19 16:29:23 +0000581 const char* const mName;
582
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700583 int mValue;
584
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700585 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700586 const String8 mVsyncOnLabel;
587 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700588
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700589 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700590
591 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800592 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700593
594 Mutex mVsyncMutex; // Protects the following
595 nsecs_t mPhaseOffset;
596 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700597};
598
Lloyd Piquee83f9312018-02-01 12:53:17 -0800599class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700600public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800601 InjectVSyncSource() = default;
602 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700603
Lloyd Piquee83f9312018-02-01 12:53:17 -0800604 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700605 std::lock_guard<std::mutex> lock(mCallbackMutex);
606 mCallback = callback;
607 }
608
Lloyd Piquee83f9312018-02-01 12:53:17 -0800609 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700610 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700611 if (mCallback) {
612 mCallback->onVSyncEvent(when);
613 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700614 }
615
Lloyd Piquee83f9312018-02-01 12:53:17 -0800616 void setVSyncEnabled(bool) override {}
617 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700618
619private:
620 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800621 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700622};
623
Wei Wangf9b05ee2017-07-19 20:59:39 -0700624// Do not call property_set on main thread which will be blocked by init
625// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700626void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700627 ALOGI( "SurfaceFlinger's main thread ready to run. "
628 "Initializing graphics H/W...");
629
Thierry Strudel2924d012017-08-14 15:19:37 -0700630 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900631
Steven Thomasb02664d2017-07-26 18:48:28 -0700632 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800633
Steven Thomasb02664d2017-07-26 18:48:28 -0700634 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800635 mEventThreadSource =
636 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
637 true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800638 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
639 [this]() { resyncWithRateLimit(); },
640 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800641 "appEventThread");
642 mSfEventThreadSource =
643 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
644 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800645
Lloyd Pique24b0a482018-03-09 18:52:26 -0800646 mSFEventThread =
647 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
648 [this]() { resyncWithRateLimit(); },
649 [this](nsecs_t timestamp) {
650 mInterceptor->saveVSyncEvent(timestamp);
651 },
652 "sfEventThread");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800653 mEventQueue->setEventThread(mSFEventThread.get());
Dan Stoza2713c302018-03-28 17:07:36 -0700654 mVsyncModulator.setEventThread(mSFEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800655
Steven Thomasb02664d2017-07-26 18:48:28 -0700656 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800657 getBE().mRenderEngine =
658 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
659 hasWideColorDisplay
660 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
661 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800662 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700663
664 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
665 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800666 getBE().mHwc.reset(
667 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700668 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800669 // Process any initial hotplug and resulting display changes.
670 processDisplayHotplugEventsLocked();
671 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
672 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800673
Lloyd Piquefcd86612017-12-14 17:15:36 -0800674 // make the default display GLContext current so that we can create textures
675 // when creating Layers (which may happens before we render something)
676 getDefaultDisplayDeviceLocked()->makeCurrent();
677
Steven Thomas050b2c82017-03-06 11:45:16 -0800678 if (useVrFlinger) {
679 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700680 // This callback is called from the vr flinger dispatch thread. We
681 // need to call signalTransaction(), which requires holding
682 // mStateLock when we're not on the main thread. Acquiring
683 // mStateLock from the vr flinger dispatch thread might trigger a
684 // deadlock in surface flinger (see b/66916578), so post a message
685 // to be handled on the main thread instead.
686 sp<LambdaMessage> message = new LambdaMessage([=]() {
687 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
688 mVrFlingerRequestsDisplay = requestDisplay;
689 signalTransaction();
690 });
691 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800692 };
David Sodman105b7dc2017-11-04 20:28:14 -0700693 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
694 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800695 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800696 if (!mVrFlinger) {
697 ALOGE("Failed to start vrflinger");
698 }
699 }
700
Lloyd Pique0c3a8832018-01-22 17:31:47 -0800701 mEventControlThread = std::make_unique<impl::EventControlThread>(
702 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700703
Mathias Agopian92a979a2012-08-02 18:32:23 -0700704 // initialize our drawing state
705 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700706
Andy McFadden13a082e2012-08-24 10:16:42 -0700707 // set initial conditions (e.g. unblank default device)
708 initializeDisplays();
709
David Sodmanbc815282017-11-05 18:57:52 -0800710 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700711
Wei Wangf9b05ee2017-07-19 20:59:39 -0700712 // Inform native graphics APIs whether the present timestamp is supported:
713 if (getHwComposer().hasCapability(
714 HWC2::Capability::PresentFenceIsNotReliable)) {
715 mStartPropertySetThread = new StartPropertySetThread(false);
716 } else {
717 mStartPropertySetThread = new StartPropertySetThread(true);
718 }
719
720 if (mStartPropertySetThread->Start() != NO_ERROR) {
721 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800722 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800723
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800724 mLegacySrgbSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(HWC_DISPLAY_PRIMARY,
725 Dataspace::SRGB_LINEAR);
726
Dan Stoza9e56aa02015-11-02 13:00:03 -0800727 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700728}
729
Romain Guy11d63f42017-07-20 12:47:14 -0700730void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700731 Mutex::Autolock _l(mStateLock);
732
Romain Guy11d63f42017-07-20 12:47:14 -0700733 char value[PROPERTY_VALUE_MAX];
734
735 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800736 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700737 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800738 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100739
740 property_get("persist.sys.sf.native_mode", value, "0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800741 mDisplayColorSetting = toDisplayColorSetting(atoi(value));
742 ALOGV("Display Color Setting is set to %s.",
743 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Romain Guy11d63f42017-07-20 12:47:14 -0700744}
745
Mathias Agopiana67e4182012-06-19 17:26:12 -0700746void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800747 // Start boot animation service by setting a property mailbox
748 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700749 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800750 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700751 if (mStartPropertySetThread->join() != NO_ERROR) {
752 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800753 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700754}
755
Mathias Agopian875d8e12013-06-07 15:35:48 -0700756size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800757 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700758}
759
Mathias Agopian875d8e12013-06-07 15:35:48 -0700760size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800761 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700762}
763
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800764// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800765
Jamie Gennis582270d2011-08-17 18:19:00 -0700766bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800767 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800768 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800769 return authenticateSurfaceTextureLocked(bufferProducer);
770}
771
772bool SurfaceFlinger::authenticateSurfaceTextureLocked(
773 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800774 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800775 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800776}
777
Brian Anderson6b376712017-04-04 10:51:39 -0700778status_t SurfaceFlinger::getSupportedFrameTimestamps(
779 std::vector<FrameEvent>* outSupported) const {
780 *outSupported = {
781 FrameEvent::REQUESTED_PRESENT,
782 FrameEvent::ACQUIRE,
783 FrameEvent::LATCH,
784 FrameEvent::FIRST_REFRESH_START,
785 FrameEvent::LAST_REFRESH_START,
786 FrameEvent::GPU_COMPOSITION_DONE,
787 FrameEvent::DEQUEUE_READY,
788 FrameEvent::RELEASE,
789 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700790 ConditionalLock _l(mStateLock,
791 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700792 if (!getHwComposer().hasCapability(
793 HWC2::Capability::PresentFenceIsNotReliable)) {
794 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
795 }
796 return NO_ERROR;
797}
798
Dan Stoza7f7da322014-05-02 15:26:25 -0700799status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
800 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800801 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700802 return BAD_VALUE;
803 }
804
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500805 if (!display.get())
806 return NAME_NOT_FOUND;
807
Jesse Hall692c7232012-11-08 15:41:56 -0800808 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700809 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800810 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700811 type = i;
812 break;
813 }
814 }
815
816 if (type < 0) {
817 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700818 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700819
Mathias Agopian8b736f12012-08-13 17:54:26 -0700820 // TODO: Not sure if display density should handled by SF any longer
821 class Density {
822 static int getDensityFromProperty(char const* propName) {
823 char property[PROPERTY_VALUE_MAX];
824 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800825 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700826 density = atoi(property);
827 }
828 return density;
829 }
830 public:
831 static int getEmuDensity() {
832 return getDensityFromProperty("qemu.sf.lcd_density"); }
833 static int getBuildDensity() {
834 return getDensityFromProperty("ro.sf.lcd_density"); }
835 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700836
Dan Stoza7f7da322014-05-02 15:26:25 -0700837 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700838
Steven Thomas6d8110b2017-08-31 18:24:21 -0700839 ConditionalLock _l(mStateLock,
840 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800841 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700842 DisplayInfo info = DisplayInfo();
843
Dan Stoza9e56aa02015-11-02 13:00:03 -0800844 float xdpi = hwConfig->getDpiX();
845 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700846
847 if (type == DisplayDevice::DISPLAY_PRIMARY) {
848 // The density of the device is provided by a build property
849 float density = Density::getBuildDensity() / 160.0f;
850 if (density == 0) {
851 // the build doesn't provide a density -- this is wrong!
852 // use xdpi instead
853 ALOGE("ro.sf.lcd_density must be defined as a build property");
854 density = xdpi / 160.0f;
855 }
856 if (Density::getEmuDensity()) {
857 // if "qemu.sf.lcd_density" is specified, it overrides everything
858 xdpi = ydpi = density = Density::getEmuDensity();
859 density /= 160.0f;
860 }
861 info.density = density;
862
863 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700864 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800865 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700866 } else {
867 // TODO: where should this value come from?
868 static const int TV_DENSITY = 213;
869 info.density = TV_DENSITY / 160.0f;
870 info.orientation = 0;
871 }
872
Dan Stoza9e56aa02015-11-02 13:00:03 -0800873 info.w = hwConfig->getWidth();
874 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700875 info.xdpi = xdpi;
876 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800877 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900878 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800879
Andy McFadden91b2ca82014-06-13 14:04:23 -0700880 // This is how far in advance a buffer must be queued for
881 // presentation at a given time. If you want a buffer to appear
882 // on the screen at time N, you must submit the buffer before
883 // (N - presentationDeadline).
884 //
885 // Normally it's one full refresh period (to give SF a chance to
886 // latch the buffer), but this can be reduced by configuring a
887 // DispSync offset. Any additional delays introduced by the hardware
888 // composer or panel must be accounted for here.
889 //
890 // We add an additional 1ms to allow for processing time and
891 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800892 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800893 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700894
895 // All non-virtual displays are currently considered secure.
896 info.secure = true;
897
Michael Wright28f24d02016-07-12 13:30:53 -0700898 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700899 }
900
Dan Stoza7f7da322014-05-02 15:26:25 -0700901 return NO_ERROR;
902}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700903
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800904status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700905 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800906 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700907 return BAD_VALUE;
908 }
909
910 // FIXME for now we always return stats for the primary display
911 memset(stats, 0, sizeof(*stats));
912 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
913 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
914 return NO_ERROR;
915}
916
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700917int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800918 if (display == nullptr) {
919 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800920 return BAD_VALUE;
921 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700922
923 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800924 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700925 return device->getActiveConfig();
926 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700927
Dan Stoza24a42e92015-03-09 10:04:11 -0700928 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700929}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700930
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700931void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
932 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
933 this);
934 int32_t type = hw->getDisplayType();
935 int currentMode = hw->getActiveConfig();
936
937 if (mode == currentMode) {
938 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
939 return;
940 }
941
942 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
943 ALOGW("Trying to set config for virtual display");
944 return;
945 }
946
947 hw->setActiveConfig(mode);
948 getHwComposer().setActiveConfig(type, mode);
949}
950
951status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
952 class MessageSetActiveConfig: public MessageBase {
953 SurfaceFlinger& mFlinger;
954 sp<IBinder> mDisplay;
955 int mMode;
956 public:
957 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
958 int mode) :
959 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
960 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700961 Vector<DisplayInfo> configs;
962 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700963 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700964 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700965 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700966 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700967 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700968 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800969 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700970 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700971 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700972 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
973 ALOGW("Attempt to set active config = %d for virtual display",
974 mMode);
975 } else {
976 mFlinger.setActiveConfigInternal(hw, mMode);
977 }
978 return true;
979 }
980 };
981 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
982 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700983 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700984}
Michael Wright28f24d02016-07-12 13:30:53 -0700985status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -0700986 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700987 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
988 return BAD_VALUE;
989 }
990
991 if (!display.get()) {
992 return NAME_NOT_FOUND;
993 }
994
995 int32_t type = NAME_NOT_FOUND;
996 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
997 if (display == mBuiltinDisplays[i]) {
998 type = i;
999 break;
1000 }
1001 }
1002
1003 if (type < 0) {
1004 return type;
1005 }
1006
Peiyong Lina52f0292018-03-14 17:26:31 -07001007 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001008 {
1009 ConditionalLock _l(mStateLock,
1010 std::this_thread::get_id() != mMainThreadId);
1011 modes = getHwComposer().getColorModes(type);
1012 }
Michael Wright28f24d02016-07-12 13:30:53 -07001013 outColorModes->clear();
1014 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1015
1016 return NO_ERROR;
1017}
1018
Peiyong Lina52f0292018-03-14 17:26:31 -07001019ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001020 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -07001021 if (device != nullptr) {
1022 return device->getActiveColorMode();
1023 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001024 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001025}
1026
1027void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001028 ColorMode mode, Dataspace dataSpace,
1029 RenderIntent renderIntent) {
Michael Wright28f24d02016-07-12 13:30:53 -07001030 int32_t type = hw->getDisplayType();
Peiyong Lina52f0292018-03-14 17:26:31 -07001031 ColorMode currentMode = hw->getActiveColorMode();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001032 Dataspace currentDataSpace = hw->getCompositionDataSpace();
Peiyong Lin38e9a562018-04-10 16:24:20 -07001033 RenderIntent currentRenderIntent = hw->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001034
Peiyong Lin38e9a562018-04-10 16:24:20 -07001035 if (mode == currentMode && dataSpace == currentDataSpace &&
1036 renderIntent == currentRenderIntent) {
1037 return;
1038 }
1039
1040 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1041 ALOGW("Trying to set config for virtual display");
1042 return;
1043 }
1044
1045 hw->setActiveColorMode(mode);
1046 hw->setCompositionDataSpace(dataSpace);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001047 hw->setActiveRenderIntent(renderIntent);
1048 getHwComposer().setActiveColorMode(type, mode, renderIntent);
1049
1050 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
1051 decodeColorMode(mode).c_str(), mode,
1052 decodeRenderIntent(renderIntent).c_str(), renderIntent,
1053 hw->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001054}
1055
1056
1057status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001058 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -07001059 class MessageSetActiveColorMode: public MessageBase {
1060 SurfaceFlinger& mFlinger;
1061 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -07001062 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001063 public:
1064 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -07001065 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -07001066 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1067 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -07001068 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001069 mFlinger.getDisplayColorModes(mDisplay, &modes);
1070 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -07001071 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001072 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1073 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001074 return true;
1075 }
1076 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1077 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001078 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1079 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001080 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001081 ALOGW("Attempt to set active color mode %s %d for virtual display",
1082 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001083 } else {
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001084 mFlinger.setActiveColorModeInternal(hw, mMode, Dataspace::UNKNOWN,
1085 RenderIntent::COLORIMETRIC);
Michael Wright28f24d02016-07-12 13:30:53 -07001086 }
1087 return true;
1088 }
1089 };
1090 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1091 postMessageSync(msg);
1092 return NO_ERROR;
1093}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001094
Svetoslavd85084b2014-03-20 10:28:31 -07001095status_t SurfaceFlinger::clearAnimationFrameStats() {
1096 Mutex::Autolock _l(mStateLock);
1097 mAnimFrameTracker.clearStats();
1098 return NO_ERROR;
1099}
1100
1101status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1102 Mutex::Autolock _l(mStateLock);
1103 mAnimFrameTracker.getStats(outStats);
1104 return NO_ERROR;
1105}
1106
Dan Stozac4f471e2016-03-24 09:31:08 -07001107status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1108 HdrCapabilities* outCapabilities) const {
1109 Mutex::Autolock _l(mStateLock);
1110
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001111 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001112 if (displayDevice == nullptr) {
1113 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1114 return BAD_VALUE;
1115 }
1116
Peiyong Linfb069302018-04-25 14:34:31 -07001117 // At this point the DisplayDeivce should already be set up,
1118 // meaning the luminance information is already queried from
1119 // hardware composer and stored properly.
1120 const HdrCapabilities& capabilities = displayDevice->getHdrCapabilities();
1121 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1122 capabilities.getDesiredMaxLuminance(),
1123 capabilities.getDesiredMaxAverageLuminance(),
1124 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001125
1126 return NO_ERROR;
1127}
1128
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001129status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001130 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1131 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001132
Chia-I Wu90f669f2017-10-05 14:24:41 -07001133 if (mInjectVSyncs == enable) {
1134 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001135 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001136
1137 if (enable) {
1138 ALOGV("VSync Injections enabled");
1139 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001140 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001141 mInjectorEventThread = std::make_unique<
1142 impl::EventThread>(mVSyncInjector.get(),
1143 [this]() { resyncWithRateLimit(); },
1144 impl::EventThread::InterceptVSyncsCallback(),
1145 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001146 }
Lloyd Pique9123ae52018-01-22 17:14:00 -08001147 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001148 } else {
1149 ALOGV("VSync Injections disabled");
Lloyd Pique9123ae52018-01-22 17:14:00 -08001150 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001151 }
1152
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001153 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001154 });
1155 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001156 return NO_ERROR;
1157}
1158
1159status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001160 Mutex::Autolock _l(mStateLock);
1161
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001162 if (!mInjectVSyncs) {
1163 ALOGE("VSync Injections not enabled");
1164 return BAD_VALUE;
1165 }
1166 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1167 ALOGV("Injecting VSync inside SurfaceFlinger");
1168 mVSyncInjector->onInjectSyncEvent(when);
1169 }
1170 return NO_ERROR;
1171}
1172
Lloyd Pique755e3192018-01-31 16:46:15 -08001173status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1174 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001175 IPCThreadState* ipc = IPCThreadState::self();
1176 const int pid = ipc->getCallingPid();
1177 const int uid = ipc->getCallingUid();
1178 if ((uid != AID_SHELL) &&
1179 !PermissionCache::checkPermission(sDump, pid, uid)) {
1180 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1181 return PERMISSION_DENIED;
1182 }
1183
1184 // Try to acquire a lock for 1s, fail gracefully
1185 const status_t err = mStateLock.timedLock(s2ns(1));
1186 const bool locked = (err == NO_ERROR);
1187 if (!locked) {
1188 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1189 return TIMED_OUT;
1190 }
1191
1192 outLayers->clear();
1193 mCurrentState.traverseInZOrder([&](Layer* layer) {
1194 outLayers->push_back(layer->getLayerDebugInfo());
1195 });
1196
1197 mStateLock.unlock();
1198 return NO_ERROR;
1199}
1200
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001201// ----------------------------------------------------------------------------
1202
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001203sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1204 ISurfaceComposer::VsyncSource vsyncSource) {
1205 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1206 return mSFEventThread->createEventConnection();
1207 } else {
1208 return mEventThread->createEventConnection();
1209 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001210}
1211
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001212// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001213
1214void SurfaceFlinger::waitForEvent() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001215 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001216}
1217
1218void SurfaceFlinger::signalTransaction() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001219 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001220}
1221
1222void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001223 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001224}
1225
1226void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001227 mRefreshPending = true;
Lloyd Pique9123ae52018-01-22 17:14:00 -08001228 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001229}
1230
1231status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001232 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001233 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001234}
1235
1236status_t SurfaceFlinger::postMessageSync(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 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001239 if (res == NO_ERROR) {
1240 msg->wait();
1241 }
1242 return res;
1243}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001244
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001245void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001246 do {
1247 waitForEvent();
1248 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001249}
1250
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001251void SurfaceFlinger::enableHardwareVsync() {
1252 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001253 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001254 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001255 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1256 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001257 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001258 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001259}
1260
Jesse Hall948fe0c2013-10-14 12:56:09 -07001261void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001262 Mutex::Autolock _l(mHWVsyncLock);
1263
Jesse Hall948fe0c2013-10-14 12:56:09 -07001264 if (makeAvailable) {
1265 mHWVsyncAvailable = true;
1266 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001267 // Hardware vsync is not currently available, so abort the resync
1268 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001269 return;
1270 }
1271
David Sodman105b7dc2017-11-04 20:28:14 -07001272 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001273 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001274
1275 mPrimaryDispSync.reset();
1276 mPrimaryDispSync.setPeriod(period);
1277
1278 if (!mPrimaryHWVsyncEnabled) {
1279 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001280 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1281 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001282 mPrimaryHWVsyncEnabled = true;
1283 }
1284}
1285
Jesse Hall948fe0c2013-10-14 12:56:09 -07001286void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001287 Mutex::Autolock _l(mHWVsyncLock);
1288 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001289 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1290 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001291 mPrimaryDispSync.endResync();
1292 mPrimaryHWVsyncEnabled = false;
1293 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001294 if (makeUnavailable) {
1295 mHWVsyncAvailable = false;
1296 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001297}
1298
Tim Murray4a4e4a22016-04-19 16:29:23 +00001299void SurfaceFlinger::resyncWithRateLimit() {
1300 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001301
1302 // No explicit locking is needed here since EventThread holds a lock while calling this method
1303 static nsecs_t sLastResyncAttempted = 0;
1304 const nsecs_t now = systemTime();
1305 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001306 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001307 }
Dan Stoza57164302017-05-08 14:03:54 -07001308 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001309}
1310
Steven Thomasb02664d2017-07-26 18:48:28 -07001311void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1312 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001313 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001314 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001315 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001316 return;
1317 }
1318
1319 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001320 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001321 return;
1322 }
1323
Jamie Gennisd1700752013-10-14 12:22:52 -07001324 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001325
Jamie Gennisd1700752013-10-14 12:22:52 -07001326 { // Scope for the lock
1327 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001328 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001329 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001330 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001331 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001332
1333 if (needsHwVsync) {
1334 enableHardwareVsync();
1335 } else {
1336 disableHardwareVsync(false);
1337 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001338}
1339
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001340void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001341 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1342 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001343}
1344
Lloyd Pique715a2c12017-12-14 17:18:08 -08001345void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1346 HWC2::Connection connection) {
1347 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1348 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001349
Lloyd Piqueba04e622017-12-14 17:11:26 -08001350 // Ignore events that do not have the right sequenceId.
1351 if (sequenceId != getBE().mComposerSequenceId) {
1352 return;
1353 }
1354
Steven Thomasb02664d2017-07-26 18:48:28 -07001355 // Only lock if we're not on the main thread. This function is normally
1356 // called on a hwbinder thread, but for the primary display it's called on
1357 // the main thread with the state lock already held, so don't attempt to
1358 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001359 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001360
Lloyd Pique715a2c12017-12-14 17:18:08 -08001361 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001362
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001363 if (std::this_thread::get_id() == mMainThreadId) {
1364 // Process all pending hot plug events immediately if we are on the main thread.
1365 processDisplayHotplugEventsLocked();
1366 }
1367
Lloyd Piqueba04e622017-12-14 17:11:26 -08001368 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001369}
1370
Steven Thomasb02664d2017-07-26 18:48:28 -07001371void SurfaceFlinger::onRefreshReceived(int sequenceId,
1372 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001373 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001374 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001375 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001376 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001377 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001378}
1379
Dan Stoza9e56aa02015-11-02 13:00:03 -08001380void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001381 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001382 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001383 getHwComposer().setVsyncEnabled(disp,
1384 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001385}
1386
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001387// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001388void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001389 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001390 // Clear the drawing state so that the logic inside of
1391 // handleTransactionLocked will fire. It will determine the delta between
1392 // mCurrentState and mDrawingState and re-apply all changes when we make the
1393 // transition.
1394 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001395 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001396 mDisplays.clear();
1397}
1398
Steven Thomas050b2c82017-03-06 11:45:16 -08001399void SurfaceFlinger::updateVrFlinger() {
1400 if (!mVrFlinger)
1401 return;
1402 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001403 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001404 return;
1405 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001406
David Sodman105b7dc2017-11-04 20:28:14 -07001407 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001408 ALOGE("Vr flinger is only supported for remote hardware composer"
1409 " service connections. Ignoring request to transition to vr"
1410 " flinger.");
1411 mVrFlingerRequestsDisplay = false;
1412 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001413 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001414
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001415 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001416
Steven Thomasb02664d2017-07-26 18:48:28 -07001417 int currentDisplayPowerMode = getDisplayDeviceLocked(
1418 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001419
Steven Thomasb02664d2017-07-26 18:48:28 -07001420 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001421 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001422 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001423
Steven Thomasb02664d2017-07-26 18:48:28 -07001424 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001425 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001426 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1427 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001428 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001429
David Sodman105b7dc2017-11-04 20:28:14 -07001430 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1431 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001432
1433 if (vrFlingerRequestsDisplay) {
1434 mVrFlinger->GrantDisplayOwnership();
1435 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001436 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001437 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001438
1439 mVisibleRegionsDirty = true;
1440 invalidateHwcGeometry();
1441
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001442 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001443 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1444 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1445 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001446
Steven Thomasb02664d2017-07-26 18:48:28 -07001447 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001448 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001449 const nsecs_t period = activeConfig->getVsyncPeriod();
1450 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001451
Steven Thomasb02664d2017-07-26 18:48:28 -07001452 // Use phase of 0 since phase is not known.
1453 // Use latency of 0, which will snap to the ideal latency.
1454 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001455
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001456 android_atomic_or(1, &mRepaintEverything);
1457 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001458}
1459
Mathias Agopian4fec8732012-06-29 14:12:52 -07001460void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001461 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001462 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001463 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001464 bool frameMissed = !mHadClientComposition &&
1465 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001466 (mPreviousPresentFence->getSignalTime() ==
1467 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001468 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001469 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001470 mTimeStats.incrementMissedFrames();
1471 if (mPropagateBackpressure) {
1472 signalLayerUpdate();
1473 break;
1474 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001475 }
Dan Stoza50182882016-07-08 12:02:20 -07001476
Steven Thomas050b2c82017-03-06 11:45:16 -08001477 // Now that we're going to make it to the handleMessageTransaction()
1478 // call below it's safe to call updateVrFlinger(), which will
1479 // potentially trigger a display handoff.
1480 updateVrFlinger();
1481
Dan Stoza6b9454d2014-11-07 16:00:59 -08001482 bool refreshNeeded = handleMessageTransaction();
1483 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001484 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001485 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001486 // Signal a refresh if a transaction modified the window state,
1487 // a new buffer was latched, or if HWC has requested a full
1488 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001489 signalRefresh();
1490 }
1491 break;
1492 }
1493 case MessageQueue::REFRESH: {
1494 handleMessageRefresh();
1495 break;
1496 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001497 }
1498}
1499
Dan Stoza6b9454d2014-11-07 16:00:59 -08001500bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001501 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001502 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001503 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001504 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001505 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001506 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001507}
1508
Dan Stoza6b9454d2014-11-07 16:00:59 -08001509bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001510 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001511 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001512}
1513
1514void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001515 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001516
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001517 mRefreshPending = false;
1518
Pablo Ceballos40845df2016-01-25 17:41:15 -08001519 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001520
Brian Andersond6927fb2016-07-23 23:37:30 -07001521 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001522 rebuildLayerStacks();
1523 setUpHWComposer();
1524 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001525 doTracing("handleRefresh");
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001526 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001527 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001528 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001529
David Sodman105b7dc2017-11-04 20:28:14 -07001530 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001531
1532 mHadClientComposition = false;
1533 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1534 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1535 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001536 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001537 }
Dan Stoza2713c302018-03-28 17:07:36 -07001538 mVsyncModulator.setLastFrameUsedRenderEngine(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001539
Dan Stoza9e56aa02015-11-02 13:00:03 -08001540 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001541}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001542
Mathias Agopiancd60f992012-08-16 16:28:27 -07001543void SurfaceFlinger::doDebugFlashRegions()
1544{
1545 // is debugging enabled
1546 if (CC_LIKELY(!mDebugRegion))
1547 return;
1548
1549 const bool repaintEverything = mRepaintEverything;
1550 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1551 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001552 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001553 // transform the dirty region into this screen's coordinate space
1554 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1555 if (!dirtyRegion.isEmpty()) {
1556 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001557 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001558
1559 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001560 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001561 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001562 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1563
Mathias Agopianda27af92012-09-13 18:17:13 -07001564 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001565 }
1566 }
1567 }
1568
1569 postFramebuffer();
1570
1571 if (mDebugRegion > 1) {
1572 usleep(mDebugRegion * 1000);
1573 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001574
Dan Stoza9e56aa02015-11-02 13:00:03 -08001575 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001576 auto& displayDevice = mDisplays[displayId];
1577 if (!displayDevice->isDisplayOn()) {
1578 continue;
1579 }
1580
David Sodman105b7dc2017-11-04 20:28:14 -07001581 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1582 ALOGE_IF(result != NO_ERROR,
1583 "prepareFrame for display %zd failed:"
1584 " %d (%s)",
1585 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001586 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001587}
1588
Adrian Roos1e1a1282017-11-01 19:05:31 +01001589void SurfaceFlinger::doTracing(const char* where) {
1590 ATRACE_CALL();
1591 ATRACE_NAME(where);
1592 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001593 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001594 }
1595}
1596
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001597void SurfaceFlinger::logLayerStats() {
1598 ATRACE_CALL();
1599 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1600 int32_t hwcId = -1;
1601 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1602 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1603 if (displayDevice->isPrimary()) {
1604 hwcId = displayDevice->getHwcDisplayId();
1605 break;
1606 }
1607 }
1608 if (hwcId < 0) {
1609 ALOGE("LayerStats: Hmmm, no primary display?");
1610 return;
1611 }
1612 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1613 }
1614}
1615
Brian Andersond6927fb2016-07-23 23:37:30 -07001616void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001617{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001618 ATRACE_CALL();
1619 ALOGV("preComposition");
1620
Mathias Agopiancd60f992012-08-16 16:28:27 -07001621 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001622 mDrawingState.traverseInZOrder([&](Layer* layer) {
1623 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001624 needExtraInvalidate = true;
1625 }
Robert Carr2047fae2016-11-28 14:09:09 -08001626 });
1627
Mathias Agopiancd60f992012-08-16 16:28:27 -07001628 if (needExtraInvalidate) {
1629 signalLayerUpdate();
1630 }
1631}
1632
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001633void SurfaceFlinger::updateCompositorTiming(
1634 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1635 std::shared_ptr<FenceTime>& presentFenceTime) {
1636 // Update queue of past composite+present times and determine the
1637 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001638 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001639 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001640 while (!getBE().mCompositePresentTimes.empty()) {
1641 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001642 // Cached values should have been updated before calling this method,
1643 // which helps avoid duplicate syscalls.
1644 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1645 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1646 break;
1647 }
1648 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001649 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001650 }
1651
1652 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001653 while (getBE().mCompositePresentTimes.size() > 16) {
1654 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001655 }
1656
Brian Andersond0010582017-03-07 13:20:31 -08001657 setCompositorTimingSnapped(
1658 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1659}
1660
1661void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1662 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001663 // Integer division and modulo round toward 0 not -inf, so we need to
1664 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001665 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001666 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1667 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1668
Brian Andersond0010582017-03-07 13:20:31 -08001669 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1670 if (idealLatency <= 0) {
1671 idealLatency = vsyncInterval;
1672 }
1673
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001674 // Snap the latency to a value that removes scheduling jitter from the
1675 // composition and present times, which often have >1ms of jitter.
1676 // Reducing jitter is important if an app attempts to extrapolate
1677 // something (such as user input) to an accurate diasplay time.
1678 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1679 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001680 nsecs_t bias = vsyncInterval / 2;
1681 int64_t extraVsyncs =
1682 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1683 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1684 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001685
David Sodman99974d22017-11-28 12:04:33 -08001686 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1687 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1688 getBE().mCompositorTiming.interval = vsyncInterval;
1689 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001690}
1691
1692void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001693{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001694 ATRACE_CALL();
1695 ALOGV("postComposition");
1696
Brian Anderson3546a3f2016-07-14 11:51:14 -07001697 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001698 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001699 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001700 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001701 }
1702
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001703 // |mStateLock| not needed as we are on the main thread
1704 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001705
David Sodman73beded2017-11-15 11:56:06 -08001706 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001707 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001708 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001709 glCompositionDoneFenceTime =
1710 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001711 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001712 } else {
1713 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1714 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001715
David Sodman73beded2017-11-15 11:56:06 -08001716 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001717 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001718 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001719 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001720
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001721 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1722 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1723
1724 // We use the refreshStartTime which might be sampled a little later than
1725 // when we started doing work for this frame, but that should be okay
1726 // since updateCompositorTiming has snapping logic.
1727 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001728 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001729 CompositorTiming compositorTiming;
1730 {
David Sodman99974d22017-11-28 12:04:33 -08001731 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1732 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001733 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001734
Robert Carr2047fae2016-11-28 14:09:09 -08001735 mDrawingState.traverseInZOrder([&](Layer* layer) {
1736 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001737 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001738 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001739 recordBufferingStats(layer->getName().string(),
1740 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001741 }
Robert Carr2047fae2016-11-28 14:09:09 -08001742 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001743
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001744 if (presentFenceTime->isValid()) {
1745 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001746 enableHardwareVsync();
1747 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001748 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001749 }
1750 }
1751
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001752 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001753 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001754 enableHardwareVsync();
1755 }
1756 }
1757
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001758 if (mAnimCompositionPending) {
1759 mAnimCompositionPending = false;
1760
Brian Anderson4e606e32017-03-16 15:34:57 -07001761 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001762 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001763 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001764 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001765 // The HWC doesn't support present fences, so use the refresh
1766 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001767 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001768 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001769 mAnimFrameTracker.setActualPresentTime(presentTime);
1770 }
1771 mAnimFrameTracker.advanceFrame();
1772 }
Dan Stozab90cf072015-03-05 11:05:59 -08001773
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001774 mTimeStats.incrementTotalFrames();
1775 if (mHadClientComposition) {
1776 mTimeStats.incrementClientCompositionFrames();
1777 }
1778
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001779 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1780 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001781 return;
1782 }
1783
1784 nsecs_t currentTime = systemTime();
1785 if (mHasPoweredOff) {
1786 mHasPoweredOff = false;
1787 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001788 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001789 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001790 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1791 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001792 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001793 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001794 }
David Sodman4a36e932017-11-07 14:29:47 -08001795 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001796 }
David Sodman4a36e932017-11-07 14:29:47 -08001797 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001798}
1799
1800void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001801 ATRACE_CALL();
1802 ALOGV("rebuildLayerStacks");
1803
Mathias Agopiancd60f992012-08-16 16:28:27 -07001804 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001805 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001806 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001807 mVisibleRegionsDirty = false;
1808 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001809
Jeff Sharkey76488112017-02-27 14:15:18 -07001810 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1811 Region opaqueRegion;
1812 Region dirtyRegion;
1813 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001814 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001815 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1816 const Transform& tr(displayDevice->getTransform());
1817 const Rect bounds(displayDevice->getBounds());
1818 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001819 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001820
Jeff Sharkey76488112017-02-27 14:15:18 -07001821 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001822 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001823 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1824 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001825 Region drawRegion(tr.transform(
1826 layer->visibleNonTransparentRegion));
1827 drawRegion.andSelf(bounds);
1828 if (!drawRegion.isEmpty()) {
1829 layersSortedByZ.add(layer);
1830 } else {
1831 // Clear out the HWC layer if this layer was
1832 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001833 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001834 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001835 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001836 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001837 // WM changes displayDevice->layerStack upon sleep/awake.
1838 // Here we make sure we delete the HWC layers even if
1839 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001840 hwcLayerDestroyed = layer->destroyHwcLayer(
1841 displayDevice->getHwcDisplayId());
1842 }
1843
1844 // If a layer is not going to get a release fence because
1845 // it is invisible, but it is also going to release its
1846 // old buffer, add it to the list of layers needing
1847 // fences.
1848 if (hwcLayerDestroyed) {
1849 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1850 mLayersWithQueuedFrames.cend(), layer);
1851 if (found != mLayersWithQueuedFrames.cend()) {
1852 layersNeedingFences.add(layer);
1853 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001854 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001855 });
1856 }
1857 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001858 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001859 displayDevice->undefinedRegion.set(bounds);
1860 displayDevice->undefinedRegion.subtractSelf(
1861 tr.transform(opaqueRegion));
1862 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001863 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001864 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001865}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001866
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001867// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001868// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001869// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001870// - Dataspace::DISPLAY_P3
1871// - Dataspace::V0_SCRGB_LINEAR
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001872// The returned HDR data space is one of
1873// - Dataspace::UNKNOWN
1874// - Dataspace::BT2020_HLG
1875// - Dataspace::BT2020_PQ
1876Dataspace SurfaceFlinger::getBestDataspace(
1877 const sp<const DisplayDevice>& displayDevice, Dataspace* outHdrDataSpace) const {
1878 Dataspace bestDataSpace = Dataspace::SRGB;
1879 *outHdrDataSpace = Dataspace::UNKNOWN;
1880
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001881 for (const auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wue1043322018-05-17 13:24:48 -07001882 switch (layer->getDrawingState().dataSpace) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001883 case Dataspace::V0_SCRGB:
1884 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001885 bestDataSpace = Dataspace::V0_SCRGB_LINEAR;
Peiyong Linf59a7192018-04-25 11:19:31 -07001886 break;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001887 case Dataspace::DISPLAY_P3:
1888 if (bestDataSpace == Dataspace::SRGB) {
1889 bestDataSpace = Dataspace::DISPLAY_P3;
1890 }
1891 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001892 case Dataspace::BT2020_PQ:
1893 case Dataspace::BT2020_ITU_PQ:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001894 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001895 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001896 case Dataspace::BT2020_HLG:
1897 case Dataspace::BT2020_ITU_HLG:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001898 // When there's mixed PQ content and HLG content, we set the HDR
1899 // data space to be BT2020_PQ and convert HLG to PQ.
1900 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1901 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001902 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001903 break;
1904 default:
1905 break;
1906 }
Romain Guy54f154a2017-10-24 21:40:32 +01001907 }
1908
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001909 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001910}
1911
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001912// Pick the ColorMode / Dataspace for the display device.
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001913void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& displayDevice,
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001914 ColorMode* outMode, Dataspace* outDataSpace,
1915 RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001916 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1917 *outMode = ColorMode::NATIVE;
1918 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001919 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001920 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001921 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001922
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001923 Dataspace hdrDataSpace;
1924 Dataspace bestDataSpace = getBestDataspace(displayDevice, &hdrDataSpace);
1925
1926 if (hdrDataSpace == Dataspace::BT2020_PQ) {
1927 // Hardware composer can handle BT2100 ColorMode only when
1928 // - colorimetrical tone mapping is supported, or
1929 // - Auto mode is turned on and enhanced tone mapping is supported.
1930 if (displayDevice->hasBT2100PQColorimetricSupport() ||
1931 (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
1932 displayDevice->hasBT2100PQEnhanceSupport())) {
1933 *outMode = ColorMode::BT2100_PQ;
1934 *outDataSpace = Dataspace::BT2020_PQ;
1935 } else if (displayDevice->hasHDR10Support()) {
1936 // Legacy HDR support. HDR layers are treated as UNKNOWN layers.
1937 hdrDataSpace = Dataspace::UNKNOWN;
1938 } else {
1939 // Simulate PQ through RenderEngine, pick DISPLAY_P3 color mode.
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001940 *outMode = ColorMode::DISPLAY_P3;
1941 *outDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001942 }
1943 } else if (hdrDataSpace == Dataspace::BT2020_HLG) {
1944 if (displayDevice->hasBT2100HLGColorimetricSupport() ||
1945 (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
1946 displayDevice->hasBT2100HLGEnhanceSupport())) {
1947 *outMode = ColorMode::BT2100_HLG;
1948 *outDataSpace = Dataspace::BT2020_HLG;
1949 } else if (displayDevice->hasHLGSupport()) {
1950 // Legacy HDR support. HDR layers are treated as UNKNOWN layers.
1951 hdrDataSpace = Dataspace::UNKNOWN;
1952 } else {
1953 // Simulate HLG through RenderEngine, pick DISPLAY_P3 color mode.
1954 *outMode = ColorMode::DISPLAY_P3;
1955 *outDataSpace = Dataspace::DISPLAY_P3;
1956 }
1957 }
1958
1959 // At this point, there's no HDR layer.
1960 if (hdrDataSpace == Dataspace::UNKNOWN) {
1961 switch (bestDataSpace) {
1962 case Dataspace::DISPLAY_P3:
1963 case Dataspace::V0_SCRGB_LINEAR:
1964 *outMode = ColorMode::DISPLAY_P3;
1965 *outDataSpace = Dataspace::DISPLAY_P3;
1966 break;
1967 default:
1968 *outMode = ColorMode::SRGB;
1969 *outDataSpace = Dataspace::SRGB;
1970 break;
1971 }
1972 }
1973 *outRenderIntent = pickRenderIntent(displayDevice, *outMode);
1974}
1975
1976RenderIntent SurfaceFlinger::pickRenderIntent(const sp<DisplayDevice>& displayDevice,
1977 ColorMode colorMode) const {
1978 // Native Mode means the display is not color managed, and whichever
1979 // render intent is picked doesn't matter, thus return
1980 // RenderIntent::COLORIMETRIC as default here.
1981 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1982 return RenderIntent::COLORIMETRIC;
1983 }
1984
1985 // In Auto Color Mode, we want to strech to panel color space, right now
1986 // only the built-in display supports it.
1987 if (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
1988 mBuiltinDisplaySupportsEnhance &&
1989 displayDevice->getDisplayType() == DisplayDevice::DISPLAY_PRIMARY) {
1990 switch (colorMode) {
1991 case ColorMode::DISPLAY_P3:
1992 case ColorMode::SRGB:
1993 return RenderIntent::ENHANCE;
1994 // In Auto Color Mode, BT2100_PQ and BT2100_HLG will only be picked
1995 // when TONE_MAP_ENHANCE or TONE_MAP_COLORIMETRIC is supported.
1996 // If TONE_MAP_ENHANCE is not supported, fall back to TONE_MAP_COLORIMETRIC.
1997 case ColorMode::BT2100_PQ:
1998 return displayDevice->hasBT2100PQEnhanceSupport() ?
1999 RenderIntent::TONE_MAP_ENHANCE : RenderIntent::TONE_MAP_COLORIMETRIC;
2000 case ColorMode::BT2100_HLG:
2001 return displayDevice->hasBT2100HLGEnhanceSupport() ?
2002 RenderIntent::TONE_MAP_ENHANCE : RenderIntent::TONE_MAP_COLORIMETRIC;
2003 // This statement shouldn't be reached, switch cases will always
2004 // cover all possible ColorMode returned by pickColorMode.
2005 default:
2006 return RenderIntent::COLORIMETRIC;
2007 }
2008 }
2009
2010 // Either enhance is not supported or we are in natural mode.
2011
2012 // Natural Mode means it's color managed and the color must be right,
2013 // thus we pick RenderIntent::COLORIMETRIC as render intent for non-HDR
2014 // content and pick RenderIntent::TONE_MAP_COLORIMETRIC for HDR content.
2015 switch (colorMode) {
2016 // In Natural Color Mode, BT2100_PQ and BT2100_HLG will only be picked
2017 // when TONE_MAP_COLORIMETRIC is supported.
2018 case ColorMode::BT2100_PQ:
2019 case ColorMode::BT2100_HLG:
2020 return RenderIntent::TONE_MAP_COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002021 default:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002022 return RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002023 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002024}
2025
Mathias Agopiancd60f992012-08-16 16:28:27 -07002026void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002027 ATRACE_CALL();
2028 ALOGV("setUpHWComposer");
2029
Jesse Hall028dc8f2013-08-20 16:35:32 -07002030 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Dan Stozac7a25ad2018-04-12 11:45:09 -07002031 bool dirty = !mDisplays[dpy]->getDirtyRegion(mRepaintEverything).isEmpty();
Jesse Hallb7a05492014-08-14 15:45:06 -07002032 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
2033 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
2034
2035 // If nothing has changed (!dirty), don't recompose.
2036 // If something changed, but we don't currently have any visible layers,
2037 // and didn't when we last did a composition, then skip it this time.
2038 // The second rule does two things:
2039 // - When all layers are removed from a display, we'll emit one black
2040 // frame, then nothing more until we get new layers.
2041 // - When a display is created with a private layer stack, we won't
2042 // emit any black frames until a layer is added to the layer stack.
2043 bool mustRecompose = dirty && !(empty && wasEmpty);
2044
2045 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2046 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
2047 mustRecompose ? "doing" : "skipping",
2048 dirty ? "+" : "-",
2049 empty ? "+" : "-",
2050 wasEmpty ? "+" : "-");
2051
Dan Stoza71433162014-02-04 16:22:36 -08002052 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07002053
2054 if (mustRecompose) {
2055 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
2056 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07002057 }
2058
Dan Stoza9e56aa02015-11-02 13:00:03 -08002059 // build the h/w work list
2060 if (CC_UNLIKELY(mGeometryInvalid)) {
2061 mGeometryInvalid = false;
2062 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2063 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
2064 const auto hwcId = displayDevice->getHwcDisplayId();
2065 if (hwcId >= 0) {
2066 const Vector<sp<Layer>>& currentLayers(
2067 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08002068 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002069 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08002070 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07002071 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002072 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002073 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07002074 }
2075 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07002076
Robert Carrae060832016-11-28 10:51:00 -08002077 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002078 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002079 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07002080 }
2081 }
2082 }
2083 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002084 }
Riley Andrews03414a12014-07-01 14:22:59 -07002085
Dan Stoza9e56aa02015-11-02 13:00:03 -08002086 // Set the per-frame data
2087 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2088 auto& displayDevice = mDisplays[displayId];
2089 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002090
Dan Stoza9e56aa02015-11-02 13:00:03 -08002091 if (hwcId < 0) {
2092 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07002093 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07002094 if (mDrawingState.colorMatrixChanged) {
2095 displayDevice->setColorTransform(mDrawingState.colorMatrix);
2096 status_t result = getBE().mHwc->setColorTransform(hwcId, mDrawingState.colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002097 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
2098 "display %zd: %d", displayId, result);
2099 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002100 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wue1043322018-05-17 13:24:48 -07002101 if ((layer->getDrawingState().dataSpace == Dataspace::BT2020_PQ ||
2102 layer->getDrawingState().dataSpace == Dataspace::BT2020_ITU_PQ) &&
Peiyong Lin62665892018-04-16 11:07:44 -07002103 !displayDevice->hasHDR10Support()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002104 layer->forceClientComposition(hwcId);
2105 }
Chia-I Wue1043322018-05-17 13:24:48 -07002106 if ((layer->getDrawingState().dataSpace == Dataspace::BT2020_HLG ||
2107 layer->getDrawingState().dataSpace == Dataspace::BT2020_ITU_HLG) &&
Peiyong Linf59a7192018-04-25 11:19:31 -07002108 !displayDevice->hasHLGSupport()) {
2109 layer->forceClientComposition(hwcId);
2110 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002111
chaviwc9232ed2017-11-14 15:31:15 -08002112 if (layer->getForceClientComposition(hwcId)) {
2113 ALOGV("[%s] Requesting Client composition", layer->getName().string());
2114 layer->setCompositionType(hwcId, HWC2::Composition::Client);
2115 continue;
2116 }
2117
Dan Stoza9e56aa02015-11-02 13:00:03 -08002118 layer->setPerFrameData(displayDevice);
2119 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002120
2121 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002122 ColorMode colorMode;
2123 Dataspace dataSpace;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002124 RenderIntent renderIntent;
2125 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
2126 setActiveColorModeInternal(displayDevice, colorMode, dataSpace, renderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002127 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002128 }
2129
Chia-I Wu28f320b2018-05-03 11:02:56 -07002130 mDrawingState.colorMatrixChanged = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002131
Dan Stoza9e56aa02015-11-02 13:00:03 -08002132 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002133 auto& displayDevice = mDisplays[displayId];
2134 if (!displayDevice->isDisplayOn()) {
2135 continue;
2136 }
2137
David Sodman105b7dc2017-11-04 20:28:14 -07002138 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002139 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2140 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002141 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002142}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002143
Mathias Agopiancd60f992012-08-16 16:28:27 -07002144void SurfaceFlinger::doComposition() {
2145 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002146 ALOGV("doComposition");
2147
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002148 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002149 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002150 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002151 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002152 // transform the dirty region into this screen's coordinate space
2153 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002154
2155 // repaint the framebuffer (if needed)
2156 doDisplayComposition(hw, dirtyRegion);
2157
Mathias Agopiancd60f992012-08-16 16:28:27 -07002158 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002159 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002160 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002161 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002162 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002163}
2164
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002165void SurfaceFlinger::postFramebuffer()
2166{
Mathias Agopian841cde52012-03-01 15:44:37 -08002167 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002168 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002169
Mathias Agopiana44b0412011-10-16 18:46:35 -07002170 const nsecs_t now = systemTime();
2171 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002172
Dan Stoza9e56aa02015-11-02 13:00:03 -08002173 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2174 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002175 if (!displayDevice->isDisplayOn()) {
2176 continue;
2177 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002178 const auto hwcId = displayDevice->getHwcDisplayId();
2179 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002180 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002181 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002182 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002183 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002184 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002185 // The layer buffer from the previous frame (if any) is released
2186 // by HWC only when the release fence from this frame (if any) is
2187 // signaled. Always get the release fence from HWC first.
2188 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002189 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002190
2191 // If the layer was client composited in the previous frame, we
2192 // need to merge with the previous client target acquire fence.
2193 // Since we do not track that, always merge with the current
2194 // client target acquire fence when it is available, even though
2195 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002196 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002197 releaseFence = Fence::merge("LayerRelease", releaseFence,
2198 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002199 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002200
Dan Stoza9e56aa02015-11-02 13:00:03 -08002201 layer->onLayerDisplayed(releaseFence);
2202 }
Chia-I Wu83806892017-11-16 10:50:20 -08002203
2204 // We've got a list of layers needing fences, that are disjoint with
2205 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2206 // supply them with the present fence.
2207 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002208 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002209 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2210 layer->onLayerDisplayed(presentFence);
2211 }
2212 }
2213
Dan Stoza9e56aa02015-11-02 13:00:03 -08002214 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002215 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002216 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002217 }
2218
Mathias Agopiana44b0412011-10-16 18:46:35 -07002219 mLastSwapBufferTime = systemTime() - now;
2220 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002221
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002222 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002223 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2224 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2225 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2226 logFrameStats();
2227 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002228 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002229}
2230
Mathias Agopian87baae12012-07-31 12:38:26 -07002231void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002232{
Mathias Agopian841cde52012-03-01 15:44:37 -08002233 ATRACE_CALL();
2234
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002235 // here we keep a copy of the drawing state (that is the state that's
2236 // going to be overwritten by handleTransactionLocked()) outside of
2237 // mStateLock so that the side-effects of the State assignment
2238 // don't happen with mStateLock held (which can cause deadlocks).
2239 State drawingState(mDrawingState);
2240
Mathias Agopianca4d3602011-05-19 15:38:14 -07002241 Mutex::Autolock _l(mStateLock);
2242 const nsecs_t now = systemTime();
2243 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002244
Mathias Agopianca4d3602011-05-19 15:38:14 -07002245 // Here we're guaranteed that some transaction flags are set
2246 // so we can call handleTransactionLocked() unconditionally.
2247 // We call getTransactionFlags(), which will also clear the flags,
2248 // with mStateLock held to guarantee that mCurrentState won't change
2249 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002250
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002251 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002252 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002253 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002254
Mathias Agopianca4d3602011-05-19 15:38:14 -07002255 mLastTransactionTime = systemTime() - now;
2256 mDebugInTransaction = 0;
2257 invalidateHwcGeometry();
2258 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002259}
2260
Lloyd Pique715a2c12017-12-14 17:18:08 -08002261DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique09594832018-01-22 17:48:03 -08002262 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002263 // Figure out whether the event is for the primary display or an
2264 // external display by matching the Hwc display id against one for a
2265 // connected display. If we did not find a match, we then check what
2266 // displays are not already connected to determine the type. If we don't
2267 // have a connected primary display, we assume the new display is meant to
2268 // be the primary display, and then if we don't have an external display,
2269 // we assume it is that.
2270 const auto primaryDisplayId =
2271 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2272 const auto externalDisplayId =
2273 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2274 if (primaryDisplayId && primaryDisplayId == display) {
2275 return DisplayDevice::DISPLAY_PRIMARY;
2276 } else if (externalDisplayId && externalDisplayId == display) {
2277 return DisplayDevice::DISPLAY_EXTERNAL;
2278 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2279 return DisplayDevice::DISPLAY_PRIMARY;
2280 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2281 return DisplayDevice::DISPLAY_EXTERNAL;
2282 }
2283
2284 return DisplayDevice::DISPLAY_ID_INVALID;
2285}
2286
Lloyd Piqueba04e622017-12-14 17:11:26 -08002287void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2288 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002289 auto displayType = determineDisplayType(event.display, event.connection);
2290 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2291 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2292 continue;
2293 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002294
2295 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2296 ALOGE("External displays are not supported by the vr hardware composer.");
2297 continue;
2298 }
2299
Lloyd Pique715a2c12017-12-14 17:18:08 -08002300 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002301
2302 if (event.connection == HWC2::Connection::Connected) {
Steven Thomas3bed0522018-03-20 15:40:48 -07002303 if (!mBuiltinDisplays[displayType].get()) {
2304 ALOGV("Creating built in display %d", displayType);
2305 mBuiltinDisplays[displayType] = new BBinder();
2306 // All non-virtual displays are currently considered secure.
2307 DisplayDeviceState info(displayType, true);
2308 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2309 "Built-in Screen" : "External Screen";
2310 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
Lloyd Pique4d234852018-01-22 17:21:36 -08002311 mInterceptor->saveDisplayCreation(info);
Steven Thomas3bed0522018-03-20 15:40:48 -07002312 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002313 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002314 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002315
Lloyd Piquefcd86612017-12-14 17:15:36 -08002316 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2317 if (idx >= 0) {
2318 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Lloyd Pique4d234852018-01-22 17:21:36 -08002319 mInterceptor->saveDisplayDeletion(info.displayId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002320 mCurrentState.displays.removeItemsAt(idx);
2321 }
2322 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002323 }
2324
2325 processDisplayChangesLocked();
2326 }
2327
2328 mPendingHotplugEvents.clear();
2329}
2330
Lloyd Pique09594832018-01-22 17:48:03 -08002331sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2332 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2333 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002334 bool hasWideColorGamut = false;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002335 std::unordered_map<ColorMode, std::vector<RenderIntent>> hdrAndRenderIntents;
2336
Lloyd Pique09594832018-01-22 17:48:03 -08002337 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002338 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Lloyd Pique09594832018-01-22 17:48:03 -08002339 for (ColorMode colorMode : modes) {
2340 switch (colorMode) {
2341 case ColorMode::DISPLAY_P3:
2342 case ColorMode::ADOBE_RGB:
2343 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002344 hasWideColorGamut = true;
Lloyd Pique09594832018-01-22 17:48:03 -08002345 break;
2346 default:
2347 break;
2348 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002349
2350 std::vector<RenderIntent> renderIntents = getHwComposer().getRenderIntents(hwcId,
2351 colorMode);
2352 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2353 for (auto intent : renderIntents) {
2354 if (intent == RenderIntent::ENHANCE) {
2355 mBuiltinDisplaySupportsEnhance = true;
2356 break;
2357 }
2358 }
2359 }
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002360
2361 if (colorMode == ColorMode::BT2100_PQ || colorMode == ColorMode::BT2100_HLG) {
2362 hdrAndRenderIntents.emplace(colorMode, renderIntents);
2363 }
Lloyd Pique09594832018-01-22 17:48:03 -08002364 }
2365 }
2366
Peiyong Lin62665892018-04-16 11:07:44 -07002367 HdrCapabilities hdrCapabilities;
2368 getHwComposer().getHdrCapabilities(hwcId, &hdrCapabilities);
Lloyd Pique09594832018-01-22 17:48:03 -08002369
2370 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2371 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2372
2373 /*
2374 * Create our display's surface
2375 */
2376 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2377 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
2378 renderSurface->setAsync(state.type >= DisplayDevice::DISPLAY_VIRTUAL);
2379 renderSurface->setNativeWindow(nativeWindow.get());
2380 const int displayWidth = renderSurface->queryWidth();
2381 const int displayHeight = renderSurface->queryHeight();
2382
2383 // Make sure that composition can never be stalled by a virtual display
2384 // consumer that isn't processing buffers fast enough. We have to do this
2385 // in two places:
2386 // * Here, in case the display is composed entirely by HWC.
2387 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2388 // window's swap interval in eglMakeCurrent, so they'll override the
2389 // interval we set here.
2390 if (state.type >= DisplayDevice::DISPLAY_VIRTUAL) {
2391 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2392 }
2393
2394 // virtual displays are always considered enabled
2395 auto initialPowerMode = (state.type >= DisplayDevice::DISPLAY_VIRTUAL) ? HWC_POWER_MODE_NORMAL
2396 : HWC_POWER_MODE_OFF;
2397
2398 sp<DisplayDevice> hw =
2399 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2400 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
Peiyong Lin2c327ac2018-04-19 22:06:34 -07002401 hasWideColorGamut, hdrCapabilities,
2402 getHwComposer().getSupportedPerFrameMetadata(hwcId),
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002403 hdrAndRenderIntents, initialPowerMode);
Lloyd Pique09594832018-01-22 17:48:03 -08002404
2405 if (maxFrameBufferAcquiredBuffers >= 3) {
2406 nativeWindowSurface->preallocateBuffers();
2407 }
2408
2409 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002410 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2411 if (hasWideColorGamut) {
Lloyd Pique09594832018-01-22 17:48:03 -08002412 defaultColorMode = ColorMode::SRGB;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002413 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique09594832018-01-22 17:48:03 -08002414 }
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002415 setActiveColorModeInternal(hw, defaultColorMode, defaultDataSpace,
2416 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002417 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
2418 hw->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
2419 }
Lloyd Pique09594832018-01-22 17:48:03 -08002420 hw->setLayerStack(state.layerStack);
2421 hw->setProjection(state.orientation, state.viewport, state.frame);
2422 hw->setDisplayName(state.displayName);
2423
2424 return hw;
2425}
2426
Lloyd Pique347200f2017-12-14 17:00:15 -08002427void SurfaceFlinger::processDisplayChangesLocked() {
2428 // here we take advantage of Vector's copy-on-write semantics to
2429 // improve performance by skipping the transaction entirely when
2430 // know that the lists are identical
2431 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2432 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2433 if (!curr.isIdenticalTo(draw)) {
2434 mVisibleRegionsDirty = true;
2435 const size_t cc = curr.size();
2436 size_t dc = draw.size();
2437
2438 // find the displays that were removed
2439 // (ie: in drawing state but not in current state)
2440 // also handle displays that changed
2441 // (ie: displays that are in both lists)
2442 for (size_t i = 0; i < dc;) {
2443 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2444 if (j < 0) {
2445 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002446 // Call makeCurrent() on the primary display so we can
2447 // be sure that nothing associated with this display
2448 // is current.
2449 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2450 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2451 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2452 if (hw != nullptr) hw->disconnect(getHwComposer());
2453 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2454 mEventThread->onHotplugReceived(draw[i].type, false);
2455 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002456 } else {
2457 // this display is in both lists. see if something changed.
2458 const DisplayDeviceState& state(curr[j]);
2459 const wp<IBinder>& display(curr.keyAt(j));
2460 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2461 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2462 if (state_binder != draw_binder) {
2463 // changing the surface is like destroying and
2464 // recreating the DisplayDevice, so we just remove it
2465 // from the drawing state, so that it get re-added
2466 // below.
2467 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2468 if (hw != nullptr) hw->disconnect(getHwComposer());
2469 mDisplays.removeItem(display);
2470 mDrawingState.displays.removeItemsAt(i);
2471 dc--;
2472 // at this point we must loop to the next item
2473 continue;
2474 }
2475
2476 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2477 if (disp != nullptr) {
2478 if (state.layerStack != draw[i].layerStack) {
2479 disp->setLayerStack(state.layerStack);
2480 }
2481 if ((state.orientation != draw[i].orientation) ||
2482 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2483 disp->setProjection(state.orientation, state.viewport, state.frame);
2484 }
2485 if (state.width != draw[i].width || state.height != draw[i].height) {
2486 disp->setDisplaySize(state.width, state.height);
2487 }
2488 }
2489 }
2490 ++i;
2491 }
2492
2493 // find displays that were added
2494 // (ie: in current state but not in drawing state)
2495 for (size_t i = 0; i < cc; i++) {
2496 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2497 const DisplayDeviceState& state(curr[i]);
2498
2499 sp<DisplaySurface> dispSurface;
2500 sp<IGraphicBufferProducer> producer;
2501 sp<IGraphicBufferProducer> bqProducer;
2502 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002503 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002504
2505 int32_t hwcId = -1;
2506 if (state.isVirtualDisplay()) {
2507 // Virtual displays without a surface are dormant:
2508 // they have external state (layer stack, projection,
2509 // etc.) but no internal state (i.e. a DisplayDevice).
2510 if (state.surface != nullptr) {
2511 // Allow VR composer to use virtual displays.
2512 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2513 int width = 0;
2514 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2515 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2516 int height = 0;
2517 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2518 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2519 int intFormat = 0;
2520 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2521 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002522 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002523
2524 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2525 }
2526
2527 // TODO: Plumb requested format back up to consumer
2528
2529 sp<VirtualDisplaySurface> vds =
2530 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2531 bqProducer, bqConsumer,
2532 state.displayName);
2533
2534 dispSurface = vds;
2535 producer = vds;
2536 }
2537 } else {
2538 ALOGE_IF(state.surface != nullptr,
2539 "adding a supported display, but rendering "
2540 "surface is provided (%p), ignoring it",
2541 state.surface.get());
2542
2543 hwcId = state.type;
2544 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2545 producer = bqProducer;
2546 }
2547
2548 const wp<IBinder>& display(curr.keyAt(i));
2549 if (dispSurface != nullptr) {
Lloyd Pique09594832018-01-22 17:48:03 -08002550 mDisplays.add(display,
2551 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2552 producer));
Lloyd Pique347200f2017-12-14 17:00:15 -08002553 if (!state.isVirtualDisplay()) {
2554 mEventThread->onHotplugReceived(state.type, true);
2555 }
2556 }
2557 }
2558 }
2559 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002560
2561 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002562}
2563
Mathias Agopian87baae12012-07-31 12:38:26 -07002564void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002565{
Dan Stoza7dde5992015-05-22 09:51:44 -07002566 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002567 mCurrentState.traverseInZOrder([](Layer* layer) {
2568 layer->notifyAvailableFrames();
2569 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002570
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002571 /*
2572 * Traversal of the children
2573 * (perform the transaction for each of them if needed)
2574 */
2575
Mathias Agopian3559b072012-08-15 13:46:03 -07002576 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002577 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002578 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002579 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002580
2581 const uint32_t flags = layer->doTransaction(0);
2582 if (flags & Layer::eVisibleRegion)
2583 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002584 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002585 }
2586
2587 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002588 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002589 */
2590
Mathias Agopiane57f2922012-08-09 16:29:12 -07002591 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002592 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002593 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002594 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002595
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002596 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002597 // The transform hint might have changed for some layers
2598 // (either because a display has changed, or because a layer
2599 // as changed).
2600 //
2601 // Walk through all the layers in currentLayers,
2602 // and update their transform hint.
2603 //
2604 // If a layer is visible only on a single display, then that
2605 // display is used to calculate the hint, otherwise we use the
2606 // default display.
2607 //
2608 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2609 // the hint is set before we acquire a buffer from the surface texture.
2610 //
2611 // NOTE: layer transactions have taken place already, so we use their
2612 // drawing state. However, SurfaceFlinger's own transaction has not
2613 // happened yet, so we must use the current state layer list
2614 // (soon to become the drawing state list).
2615 //
2616 sp<const DisplayDevice> disp;
2617 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002618 bool first = true;
2619 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002620 // NOTE: we rely on the fact that layers are sorted by
2621 // layerStack first (so we don't have to traverse the list
2622 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002623 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002624 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002625 currentlayerStack = layerStack;
2626 // figure out if this layerstack is mirrored
2627 // (more than one display) if so, pick the default display,
2628 // if not, pick the only display it's on.
2629 disp.clear();
2630 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2631 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002632 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002633 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002634 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002635 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002636 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002637 break;
2638 }
2639 }
2640 }
2641 }
Chet Haase91d25932013-04-11 15:24:55 -07002642
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002643 if (disp == nullptr) {
2644 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2645 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002646
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002647 // could be null when this layer is using a layerStack
2648 // that is not visible on any display. Also can occur at
2649 // screen off/on times.
2650 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002651 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002652
2653 // disp can be null if there is no display available at all to get
2654 // the transform hint from.
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002655 if (disp != nullptr) {
2656 layer->updateTransformHint(disp);
2657 }
Robert Carr2047fae2016-11-28 14:09:09 -08002658
2659 first = false;
2660 });
Mathias Agopian84300952012-11-21 16:02:13 -08002661 }
2662
2663
Mathias Agopian3559b072012-08-15 13:46:03 -07002664 /*
2665 * Perform our own transaction if needed
2666 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002667
2668 if (mLayersAdded) {
2669 mLayersAdded = false;
2670 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002671 mVisibleRegionsDirty = true;
2672 }
2673
2674 // some layers might have been removed, so
2675 // we need to update the regions they're exposing.
2676 if (mLayersRemoved) {
2677 mLayersRemoved = false;
2678 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002679 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002680 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002681 // this layer is not visible anymore
2682 // TODO: we could traverse the tree from front to back and
2683 // compute the actual visible region
2684 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002685 Region visibleReg;
2686 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002687 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002688 }
Robert Carr2047fae2016-11-28 14:09:09 -08002689 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002690 }
2691
2692 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002693
2694 updateCursorAsync();
2695}
2696
2697void SurfaceFlinger::updateCursorAsync()
2698{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002699 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2700 auto& displayDevice = mDisplays[displayId];
2701 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002702 continue;
2703 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002704
2705 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2706 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002707 }
2708 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002709}
2710
2711void SurfaceFlinger::commitTransaction()
2712{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002713 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002714 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002715 for (const auto& l : mLayersPendingRemoval) {
2716 recordBufferingStats(l->getName().string(),
2717 l->getOccupancyHistory(true));
2718 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002719 }
2720 mLayersPendingRemoval.clear();
2721 }
2722
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002723 // If this transaction is part of a window animation then the next frame
2724 // we composite should be considered an animation as well.
2725 mAnimCompositionPending = mAnimTransactionPending;
2726
Mathias Agopian4fec8732012-06-29 14:12:52 -07002727 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002728 // clear the "changed" flags in current state
2729 mCurrentState.colorMatrixChanged = false;
2730
Robert Carr1f0a16a2016-10-24 16:27:39 -07002731 mDrawingState.traverseInZOrder([](Layer* layer) {
2732 layer->commitChildList();
2733 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002734 mTransactionPending = false;
2735 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002736 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002737}
2738
Chia-I Wuab0c3192017-08-01 11:29:00 -07002739void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002740 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002741{
Mathias Agopian841cde52012-03-01 15:44:37 -08002742 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002743 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002744
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002745 Region aboveOpaqueLayers;
2746 Region aboveCoveredLayers;
2747 Region dirty;
2748
Mathias Agopian87baae12012-07-31 12:38:26 -07002749 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002750
Robert Carr2047fae2016-11-28 14:09:09 -08002751 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002752 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002753 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002754
Jesse Hall01e29052013-02-19 16:13:35 -08002755 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002756 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002757 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002758
Mathias Agopianab028732010-03-16 16:41:46 -07002759 /*
2760 * opaqueRegion: area of a surface that is fully opaque.
2761 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002762 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002763
2764 /*
2765 * visibleRegion: area of a surface that is visible on screen
2766 * and not fully transparent. This is essentially the layer's
2767 * footprint minus the opaque regions above it.
2768 * Areas covered by a translucent surface are considered visible.
2769 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002770 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002771
2772 /*
2773 * coveredRegion: area of a surface that is covered by all
2774 * visible regions above it (which includes the translucent areas).
2775 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002776 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002777
Jesse Halla8026d22012-09-25 13:25:04 -07002778 /*
2779 * transparentRegion: area of a surface that is hinted to be completely
2780 * transparent. This is only used to tell when the layer has no visible
2781 * non-transparent regions and can be removed from the layer list. It
2782 * does not affect the visibleRegion of this layer or any layers
2783 * beneath it. The hint may not be correct if apps don't respect the
2784 * SurfaceView restrictions (which, sadly, some don't).
2785 */
2786 Region transparentRegion;
2787
Mathias Agopianab028732010-03-16 16:41:46 -07002788
2789 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002790 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002791 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002792 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002793 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002794 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002795 if (!visibleRegion.isEmpty()) {
2796 // Remove the transparent area from the visible region
2797 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002798 if (tr.preserveRects()) {
2799 // transform the transparent region
2800 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002801 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002802 // transformation too complex, can't do the
2803 // transparent region optimization.
2804 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002805 }
Mathias Agopianab028732010-03-16 16:41:46 -07002806 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002807
Mathias Agopianab028732010-03-16 16:41:46 -07002808 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002809 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002810 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002811 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2812 // the opaque region is the layer's footprint
2813 opaqueRegion = visibleRegion;
2814 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002815 }
2816 }
2817
Robert Carre5f4f692018-01-12 13:12:28 -08002818 if (visibleRegion.isEmpty()) {
2819 layer->clearVisibilityRegions();
2820 return;
2821 }
2822
Mathias Agopianab028732010-03-16 16:41:46 -07002823 // Clip the covered region to the visible region
2824 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2825
2826 // Update aboveCoveredLayers for next (lower) layer
2827 aboveCoveredLayers.orSelf(visibleRegion);
2828
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002829 // subtract the opaque region covered by the layers above us
2830 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002831
2832 // compute this layer's dirty region
2833 if (layer->contentDirty) {
2834 // we need to invalidate the whole region
2835 dirty = visibleRegion;
2836 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002837 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002838 layer->contentDirty = false;
2839 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002840 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002841 * the exposed region consists of two components:
2842 * 1) what's VISIBLE now and was COVERED before
2843 * 2) what's EXPOSED now less what was EXPOSED before
2844 *
2845 * note that (1) is conservative, we start with the whole
2846 * visible region but only keep what used to be covered by
2847 * something -- which mean it may have been exposed.
2848 *
2849 * (2) handles areas that were not covered by anything but got
2850 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002851 */
Mathias Agopianab028732010-03-16 16:41:46 -07002852 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002853 const Region oldVisibleRegion = layer->visibleRegion;
2854 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002855 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2856 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002857 }
2858 dirty.subtractSelf(aboveOpaqueLayers);
2859
2860 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002861 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002862
Mathias Agopianab028732010-03-16 16:41:46 -07002863 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002864 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002865
Jesse Halla8026d22012-09-25 13:25:04 -07002866 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002867 layer->setVisibleRegion(visibleRegion);
2868 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002869 layer->setVisibleNonTransparentRegion(
2870 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002871 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002872
Mathias Agopian87baae12012-07-31 12:38:26 -07002873 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002874}
2875
Chia-I Wuab0c3192017-08-01 11:29:00 -07002876void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002877 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002878 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002879 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002880 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002881 }
2882 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002883}
2884
Dan Stoza6b9454d2014-11-07 16:00:59 -08002885bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002886{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002887 ALOGV("handlePageFlip");
2888
Brian Andersond6927fb2016-07-23 23:37:30 -07002889 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002890
Mathias Agopian4fec8732012-06-29 14:12:52 -07002891 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002892 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002893 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002894
2895 // Store the set of layers that need updates. This set must not change as
2896 // buffers are being latched, as this could result in a deadlock.
2897 // Example: Two producers share the same command stream and:
2898 // 1.) Layer 0 is latched
2899 // 2.) Layer 0 gets a new frame
2900 // 2.) Layer 1 gets a new frame
2901 // 3.) Layer 1 is latched.
2902 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2903 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002904 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002905 if (layer->hasQueuedFrame()) {
2906 frameQueued = true;
2907 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002908 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002909 } else {
2910 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002911 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002912 } else {
2913 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002914 }
Robert Carr2047fae2016-11-28 14:09:09 -08002915 });
2916
Dan Stoza9e56aa02015-11-02 13:00:03 -08002917 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002918 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002919 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002920 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002921 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002922 newDataLatched = true;
2923 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002924 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002925
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002926 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002927
2928 // If we will need to wake up at some time in the future to deal with a
2929 // queued frame that shouldn't be displayed during this vsync period, wake
2930 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002931 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002932 signalLayerUpdate();
2933 }
2934
2935 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002936 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002937}
2938
Mathias Agopianad456f92011-01-13 17:53:01 -08002939void SurfaceFlinger::invalidateHwcGeometry()
2940{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002941 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002942}
2943
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002944
Fabien Sanglard830b8472016-11-30 16:35:58 -08002945void SurfaceFlinger::doDisplayComposition(
2946 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002947 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002948{
Dan Stoza71433162014-02-04 16:22:36 -08002949 // We only need to actually compose the display if:
2950 // 1) It is being handled by hardware composer, which may need this to
2951 // keep its virtual display state machine in sync, or
2952 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002953 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002954 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002955 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002956 return;
2957 }
2958
Dan Stoza9e56aa02015-11-02 13:00:03 -08002959 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002960 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002961
2962 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002963 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002964}
2965
Chia-I Wub02087d2017-11-09 10:19:54 -08002966bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002967{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002968 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002969
Chia-I Wub02087d2017-11-09 10:19:54 -08002970 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002971 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002972 const auto hwcId = displayDevice->getHwcDisplayId();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002973 const bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002974 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002975
Chia-I Wu8e50e692018-05-04 10:12:37 -07002976 bool applyColorMatrix = false;
Peiyong Lin76dd77a2018-05-09 15:35:33 -07002977 bool needsLegacyColorMatrix = false;
2978 bool legacyColorMatrixApplied = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002979
Dan Stoza9e56aa02015-11-02 13:00:03 -08002980 if (hasClientComposition) {
2981 ALOGV("hasClientComposition");
2982
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002983 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002984 if (displayDevice->hasWideColorGamut()) {
2985 outputDataspace = displayDevice->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002986 }
2987 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002988 getBE().mRenderEngine->setDisplayMaxLuminance(
2989 displayDevice->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002990
Chia-I Wu8e50e692018-05-04 10:12:37 -07002991 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
2992 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2993 HWC2::Capability::SkipClientColorTransform);
2994
2995 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2996 if (applyColorMatrix) {
Peiyong Lin76dd77a2018-05-09 15:35:33 -07002997 getRenderEngine().setupColorTransform(mDrawingState.colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002998 }
2999
Peiyong Lin76dd77a2018-05-09 15:35:33 -07003000 needsLegacyColorMatrix = (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07003001 outputDataspace != Dataspace::UNKNOWN &&
3002 outputDataspace != Dataspace::SRGB);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003003
Chia-I Wu7f402902017-11-09 12:51:10 -08003004 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003005 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003006 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08003007 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003008
3009 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08003010 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07003011 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
3012 }
3013 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003014 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003015
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003016 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003017 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003018 // when using overlays, we assume a fully transparent framebuffer
3019 // NOTE: we could reduce how much we need to clear, for instance
3020 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003021 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003022 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003023 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003024 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003025 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003026 // we're left with the letterbox region
3027 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08003028 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07003029
3030 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08003031 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07003032
Mathias Agopianb9494d52012-04-18 02:28:45 -07003033 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003034 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003035 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08003036 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003037 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003038 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003039
Dan Stoza9e56aa02015-11-02 13:00:03 -08003040 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07003041 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07003042 // scissor on the main display. It should never be needed
3043 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08003044 const Rect& bounds(displayDevice->getBounds());
3045 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003046 if (scissor != bounds) {
3047 // scissor doesn't match the screen's dimensions, so we
3048 // need to clear everything outside of it and enable
3049 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003050
Mathias Agopianf45c5102012-10-24 16:29:17 -07003051 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08003052 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08003053 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07003054 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003055 }
3056 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003057 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003058
Mathias Agopian85d751c2012-08-29 16:59:24 -07003059 /*
3060 * and then, render the layers targeted at the framebuffer
3061 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003062
Dan Stoza9e56aa02015-11-02 13:00:03 -08003063 ALOGV("Rendering client layers");
3064 const Transform& displayTransform = displayDevice->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003065 bool firstLayer = true;
3066 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
3067 const Region clip(bounds.intersect(
3068 displayTransform.transform(layer->visibleRegion)));
3069 ALOGV("Layer: %s", layer->getName().string());
3070 ALOGV(" Composition type: %s",
3071 to_string(layer->getCompositionType(hwcId)).c_str());
3072 if (!clip.isEmpty()) {
3073 switch (layer->getCompositionType(hwcId)) {
3074 case HWC2::Composition::Cursor:
3075 case HWC2::Composition::Device:
3076 case HWC2::Composition::Sideband:
3077 case HWC2::Composition::SolidColor: {
3078 const Layer::State& state(layer->getDrawingState());
3079 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
3080 layer->isOpaque(state) && (state.color.a == 1.0f)
3081 && hasClientComposition) {
3082 // never clear the very first layer since we're
3083 // guaranteed the FB is already cleared
3084 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003085 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003086 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003087 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003088 case HWC2::Composition::Client: {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003089 // switch color matrices lazily
Peiyong Lin76dd77a2018-05-09 15:35:33 -07003090 if (layer->isLegacyDataSpace() && needsLegacyColorMatrix) {
3091 if (!legacyColorMatrixApplied) {
3092 getRenderEngine().setSaturationMatrix(mLegacySrgbSaturationMatrix);
3093 legacyColorMatrixApplied = true;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003094 }
Peiyong Lin76dd77a2018-05-09 15:35:33 -07003095 } else if (legacyColorMatrixApplied) {
3096 getRenderEngine().setSaturationMatrix(mat4());
3097 legacyColorMatrixApplied = false;
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003098 }
Chia-I Wu8e50e692018-05-04 10:12:37 -07003099
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003100 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003101 break;
3102 }
3103 default:
3104 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003105 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003106 } else {
3107 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003108 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003109 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003110 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003111
Peiyong Lin76dd77a2018-05-09 15:35:33 -07003112 if (applyColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003113 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003114 }
Peiyong Lin76dd77a2018-05-09 15:35:33 -07003115 if (needsLegacyColorMatrix && legacyColorMatrixApplied) {
3116 getRenderEngine().setSaturationMatrix(mat4());
3117 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003118
Mathias Agopianf45c5102012-10-24 16:29:17 -07003119 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003120 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003121 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003122}
3123
Fabien Sanglard830b8472016-11-30 16:35:58 -08003124void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
3125 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003126 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003127 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003128}
3129
Dan Stoza7d89d062015-04-30 13:29:25 -07003130status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003131 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003132 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003133 const sp<Layer>& lbc,
3134 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003135{
Dan Stoza7d89d062015-04-30 13:29:25 -07003136 // add this layer to the current state list
3137 {
3138 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003139 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003140 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3141 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003142 return NO_MEMORY;
3143 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003144 if (parent == nullptr) {
3145 mCurrentState.layersSortedByZ.add(lbc);
3146 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003147 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003148 ALOGE("addClientLayer called with a removed parent");
3149 return NAME_NOT_FOUND;
3150 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003151 parent->addChild(lbc);
3152 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003153
Yiwei Zhang243b3782018-05-15 17:40:04 -07003154 if (gbc != nullptr) {
3155 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3156 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3157 mMaxGraphicBufferProducerListSize,
3158 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3159 mGraphicBufferProducerList.size(),
3160 mMaxGraphicBufferProducerListSize, mNumLayers);
3161 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003162 mLayersAdded = true;
3163 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003164 }
3165
Mathias Agopian96f08192010-06-02 23:28:45 -07003166 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003167 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003168
Dan Stoza7d89d062015-04-30 13:29:25 -07003169 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003170}
3171
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003172status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003173 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003174 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3175}
Robert Carr7f9b8992017-03-10 11:08:39 -08003176
chaviwca27f252018-02-06 16:46:39 -08003177status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3178 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003179 if (layer->isPendingRemoval()) {
3180 return NO_ERROR;
3181 }
3182
Robert Carr1f0a16a2016-10-24 16:27:39 -07003183 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003184 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003185 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003186 if (topLevelOnly) {
3187 return NO_ERROR;
3188 }
3189
Chia-I Wu98f1c102017-05-30 14:54:08 -07003190 sp<Layer> ancestor = p;
3191 while (ancestor->getParent() != nullptr) {
3192 ancestor = ancestor->getParent();
3193 }
3194 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3195 ALOGE("removeLayer called with a layer whose parent has been removed");
3196 return NAME_NOT_FOUND;
3197 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003198
3199 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003200 } else {
3201 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003202 }
3203
Robert Carr136e2f62017-02-08 17:54:29 -08003204 // As a matter of normal operation, the LayerCleaner will produce a second
3205 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3206 // so we will succeed in promoting it, but it's already been removed
3207 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3208 // otherwise something has gone wrong and we are leaking the layer.
3209 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003210 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3211 layer->getName().string(),
3212 (p != nullptr) ? p->getName().string() : "no-parent");
3213 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003214 } else if (index < 0) {
3215 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003216 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003217
Chia-I Wuc6657022017-08-15 11:18:17 -07003218 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003219 mLayersPendingRemoval.add(layer);
3220 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003221 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003222 setTransactionFlags(eTransactionNeeded);
3223 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003224}
3225
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003226uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003227 return android_atomic_release_load(&mTransactionFlags);
3228}
3229
Mathias Agopian3f844832013-08-07 21:24:32 -07003230uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003231 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3232}
3233
Mathias Agopian3f844832013-08-07 21:24:32 -07003234uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza2713c302018-03-28 17:07:36 -07003235 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3236}
3237
3238uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3239 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003240 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza2713c302018-03-28 17:07:36 -07003241 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003242 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003243 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003244 }
3245 return old;
3246}
3247
chaviwca27f252018-02-06 16:46:39 -08003248bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3249 for (const ComposerState& state : states) {
3250 // Here we need to check that the interface we're given is indeed
3251 // one of our own. A malicious client could give us a nullptr
3252 // IInterface, or one of its own or even one of our own but a
3253 // different type. All these situations would cause us to crash.
3254 if (state.client == nullptr) {
3255 return true;
3256 }
3257
3258 sp<IBinder> binder = IInterface::asBinder(state.client);
3259 if (binder == nullptr) {
3260 return true;
3261 }
3262
3263 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3264 return true;
3265 }
3266 }
3267 return false;
3268}
3269
Mathias Agopian8b33f032012-07-24 20:43:54 -07003270void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003271 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003272 const Vector<DisplayState>& displays,
3273 uint32_t flags)
3274{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003275 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003276 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003277 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003278
chaviwca27f252018-02-06 16:46:39 -08003279 if (containsAnyInvalidClientState(states)) {
3280 return;
3281 }
3282
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003283 if (flags & eAnimation) {
3284 // For window updates that are part of an animation we must wait for
3285 // previous animation "frames" to be handled.
3286 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003287 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003288 if (CC_UNLIKELY(err != NO_ERROR)) {
3289 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003290 // caller after a few seconds.
3291 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3292 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003293 mAnimTransactionPending = false;
3294 break;
3295 }
3296 }
3297 }
3298
chaviwca27f252018-02-06 16:46:39 -08003299 for (const DisplayState& display : displays) {
3300 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003301 }
3302
chaviwca27f252018-02-06 16:46:39 -08003303 for (const ComposerState& state : states) {
3304 transactionFlags |= setClientStateLocked(state);
3305 }
3306
3307 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3308 // as destroyed should only occur after setting all other states. This is to allow for a
3309 // child re-parent to happen before marking its original parent as destroyed (which would
3310 // then mark the child as destroyed).
3311 for (const ComposerState& state : states) {
3312 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003313 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003314
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003315 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3316 // anyway. This can be used as a flush mechanism for previous async transactions.
3317 // Empty animation transaction can be used to simulate back-pressure, so also force a
3318 // transaction for empty animation transactions.
3319 if (transactionFlags == 0 &&
3320 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003321 transactionFlags = eTransactionNeeded;
3322 }
3323
Mathias Agopian386aa982011-11-07 21:58:03 -08003324 if (transactionFlags) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003325 if (mInterceptor->isEnabled()) {
3326 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003327 }
Irvel468051e2016-06-13 16:44:44 -07003328
Mathias Agopian386aa982011-11-07 21:58:03 -08003329 // this triggers the transaction
Dan Stoza2713c302018-03-28 17:07:36 -07003330 const auto start = (flags & eEarlyWakeup)
3331 ? VSyncModulator::TransactionStart::EARLY
3332 : VSyncModulator::TransactionStart::NORMAL;
3333 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003334
3335 // if this is a synchronous transaction, wait for it to take effect
3336 // before returning.
3337 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003338 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003339 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003340 if (flags & eAnimation) {
3341 mAnimTransactionPending = true;
3342 }
3343 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003344 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3345 if (CC_UNLIKELY(err != NO_ERROR)) {
3346 // just in case something goes wrong in SF, return to the
3347 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003348 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3349 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003350 break;
3351 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003352 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003353 }
3354}
3355
Mathias Agopiane57f2922012-08-09 16:29:12 -07003356uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3357{
Jesse Hall9a143922012-10-04 16:29:19 -07003358 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3359 if (dpyIdx < 0)
3360 return 0;
3361
Mathias Agopiane57f2922012-08-09 16:29:12 -07003362 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003363 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003364 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003365 const uint32_t what = s.what;
3366 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003367 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003368 disp.surface = s.surface;
3369 flags |= eDisplayTransactionNeeded;
3370 }
3371 }
3372 if (what & DisplayState::eLayerStackChanged) {
3373 if (disp.layerStack != s.layerStack) {
3374 disp.layerStack = s.layerStack;
3375 flags |= eDisplayTransactionNeeded;
3376 }
3377 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003378 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003379 if (disp.orientation != s.orientation) {
3380 disp.orientation = s.orientation;
3381 flags |= eDisplayTransactionNeeded;
3382 }
3383 if (disp.frame != s.frame) {
3384 disp.frame = s.frame;
3385 flags |= eDisplayTransactionNeeded;
3386 }
3387 if (disp.viewport != s.viewport) {
3388 disp.viewport = s.viewport;
3389 flags |= eDisplayTransactionNeeded;
3390 }
3391 }
Michael Lentine47e45402014-07-18 15:34:25 -07003392 if (what & DisplayState::eDisplaySizeChanged) {
3393 if (disp.width != s.width) {
3394 disp.width = s.width;
3395 flags |= eDisplayTransactionNeeded;
3396 }
3397 if (disp.height != s.height) {
3398 disp.height = s.height;
3399 flags |= eDisplayTransactionNeeded;
3400 }
3401 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003402 }
3403 return flags;
3404}
3405
chaviwca27f252018-02-06 16:46:39 -08003406uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3407 const layer_state_t& s = composerState.state;
3408 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3409
Mathias Agopian13127d82013-03-05 17:47:11 -08003410 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003411 if (layer == nullptr) {
3412 return 0;
3413 }
3414
3415 if (layer->isPendingRemoval()) {
3416 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3417 return 0;
3418 }
3419
3420 uint32_t flags = 0;
3421
3422 const uint32_t what = s.what;
3423 bool geometryAppliesWithResize =
3424 what & layer_state_t::eGeometryAppliesWithResize;
3425 if (what & layer_state_t::ePositionChanged) {
3426 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3427 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003428 }
chaviw8b3871a2017-11-01 17:41:01 -07003429 }
3430 if (what & layer_state_t::eLayerChanged) {
3431 // NOTE: index needs to be calculated before we update the state
3432 const auto& p = layer->getParent();
3433 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003434 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003435 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003436 mCurrentState.layersSortedByZ.removeAt(idx);
3437 mCurrentState.layersSortedByZ.add(layer);
3438 // we need traversal (state changed)
3439 // AND transaction (list changed)
3440 flags |= eTransactionNeeded|eTraversalNeeded;
3441 }
chaviw8b3871a2017-11-01 17:41:01 -07003442 } else {
3443 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003444 flags |= eTransactionNeeded|eTraversalNeeded;
3445 }
3446 }
chaviw8b3871a2017-11-01 17:41:01 -07003447 }
3448 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003449 // NOTE: index needs to be calculated before we update the state
3450 const auto& p = layer->getParent();
3451 if (p == nullptr) {
3452 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3453 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3454 mCurrentState.layersSortedByZ.removeAt(idx);
3455 mCurrentState.layersSortedByZ.add(layer);
3456 // we need traversal (state changed)
3457 // AND transaction (list changed)
3458 flags |= eTransactionNeeded|eTraversalNeeded;
3459 }
3460 } else {
3461 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3462 flags |= eTransactionNeeded|eTraversalNeeded;
3463 }
chaviw8b3871a2017-11-01 17:41:01 -07003464 }
3465 }
3466 if (what & layer_state_t::eSizeChanged) {
3467 if (layer->setSize(s.w, s.h)) {
3468 flags |= eTraversalNeeded;
3469 }
3470 }
3471 if (what & layer_state_t::eAlphaChanged) {
3472 if (layer->setAlpha(s.alpha))
3473 flags |= eTraversalNeeded;
3474 }
3475 if (what & layer_state_t::eColorChanged) {
3476 if (layer->setColor(s.color))
3477 flags |= eTraversalNeeded;
3478 }
3479 if (what & layer_state_t::eMatrixChanged) {
3480 if (layer->setMatrix(s.matrix))
3481 flags |= eTraversalNeeded;
3482 }
3483 if (what & layer_state_t::eTransparentRegionChanged) {
3484 if (layer->setTransparentRegionHint(s.transparentRegion))
3485 flags |= eTraversalNeeded;
3486 }
3487 if (what & layer_state_t::eFlagsChanged) {
3488 if (layer->setFlags(s.flags, s.mask))
3489 flags |= eTraversalNeeded;
3490 }
3491 if (what & layer_state_t::eCropChanged) {
3492 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3493 flags |= eTraversalNeeded;
3494 }
3495 if (what & layer_state_t::eFinalCropChanged) {
3496 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3497 flags |= eTraversalNeeded;
3498 }
3499 if (what & layer_state_t::eLayerStackChanged) {
3500 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3501 // We only allow setting layer stacks for top level layers,
3502 // everything else inherits layer stack from its parent.
3503 if (layer->hasParent()) {
3504 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3505 layer->getName().string());
3506 } else if (idx < 0) {
3507 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3508 "that also does not appear in the top level layer list. Something"
3509 " has gone wrong.", layer->getName().string());
3510 } else if (layer->setLayerStack(s.layerStack)) {
3511 mCurrentState.layersSortedByZ.removeAt(idx);
3512 mCurrentState.layersSortedByZ.add(layer);
3513 // we need traversal (state changed)
3514 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003515 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003516 }
3517 }
3518 if (what & layer_state_t::eDeferTransaction) {
3519 if (s.barrierHandle != nullptr) {
3520 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3521 } else if (s.barrierGbp != nullptr) {
3522 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3523 if (authenticateSurfaceTextureLocked(gbp)) {
3524 const auto& otherLayer =
3525 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3526 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3527 } else {
3528 ALOGE("Attempt to defer transaction to to an"
3529 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003530 }
3531 }
chaviw8b3871a2017-11-01 17:41:01 -07003532 // We don't trigger a traversal here because if no other state is
3533 // changed, we don't want this to cause any more work
3534 }
3535 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003536 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003537 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003538 if (!hadParent) {
3539 mCurrentState.layersSortedByZ.remove(layer);
3540 }
chaviw8b3871a2017-11-01 17:41:01 -07003541 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003542 }
chaviw8b3871a2017-11-01 17:41:01 -07003543 }
3544 if (what & layer_state_t::eReparentChildren) {
3545 if (layer->reparentChildren(s.reparentHandle)) {
3546 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003547 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003548 }
chaviw8b3871a2017-11-01 17:41:01 -07003549 if (what & layer_state_t::eDetachChildren) {
3550 layer->detachChildren();
3551 }
3552 if (what & layer_state_t::eOverrideScalingModeChanged) {
3553 layer->setOverrideScalingMode(s.overrideScalingMode);
3554 // We don't trigger a traversal here because if no other state is
3555 // changed, we don't want this to cause any more work
3556 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003557 return flags;
3558}
3559
chaviwca27f252018-02-06 16:46:39 -08003560void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3561 const layer_state_t& state = composerState.state;
3562 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3563
3564 sp<Layer> layer(client->getLayerUser(state.surface));
3565 if (layer == nullptr) {
3566 return;
3567 }
3568
3569 if (layer->isPendingRemoval()) {
3570 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3571 return;
3572 }
3573
3574 if (state.what & layer_state_t::eDestroySurface) {
3575 removeLayerLocked(mStateLock, layer);
3576 }
3577}
3578
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003579status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003580 const String8& name,
3581 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003582 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliuccd34842018-03-14 12:26:23 -07003583 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003584 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003585{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003586 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003587 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003588 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003589 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003590 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003591
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003592 status_t result = NO_ERROR;
3593
3594 sp<Layer> layer;
3595
Cody Northropbc755282017-03-31 12:00:08 -06003596 String8 uniqueName = getUniqueLayerName(name);
3597
Mathias Agopian3165cc22012-08-08 19:42:09 -07003598 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3599 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003600 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003601 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003602 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003603
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003604 break;
chaviw13fdc492017-06-27 12:40:18 -07003605 case ISurfaceComposerClient::eFXSurfaceColor:
3606 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003607 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003608 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003609 break;
3610 default:
3611 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003612 break;
3613 }
3614
Dan Stoza7d89d062015-04-30 13:29:25 -07003615 if (result != NO_ERROR) {
3616 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003617 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003618
Chia-I Wuab0c3192017-08-01 11:29:00 -07003619 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3620 // TODO b/64227542
3621 if (windowType == 441731) {
3622 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3623 layer->setPrimaryDisplayOnly();
3624 }
3625
Albert Chaulk479c60c2017-01-27 14:21:34 -05003626 layer->setInfo(windowType, ownerUid);
3627
Robert Carr1f0a16a2016-10-24 16:27:39 -07003628 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003629 if (result != NO_ERROR) {
3630 return result;
3631 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003632 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003633
3634 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003635 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003636}
3637
Cody Northropbc755282017-03-31 12:00:08 -06003638String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3639{
3640 bool matchFound = true;
3641 uint32_t dupeCounter = 0;
3642
3643 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3644 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3645
3646 // Loop over layers until we're sure there is no matching name
3647 while (matchFound) {
3648 matchFound = false;
3649 mDrawingState.traverseInZOrder([&](Layer* layer) {
3650 if (layer->getName() == uniqueName) {
3651 matchFound = true;
3652 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3653 }
3654 });
3655 }
3656
3657 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3658
3659 return uniqueName;
3660}
3661
David Sodman0c69cad2017-08-21 12:12:51 -07003662status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003663 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3664 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003665{
3666 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003667 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003668 case PIXEL_FORMAT_TRANSPARENT:
3669 case PIXEL_FORMAT_TRANSLUCENT:
3670 format = PIXEL_FORMAT_RGBA_8888;
3671 break;
3672 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003673 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003674 break;
3675 }
3676
David Sodman0c69cad2017-08-21 12:12:51 -07003677 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3678 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003679 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003680 *handle = layer->getHandle();
3681 *gbp = layer->getProducer();
3682 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003683 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003684
David Sodman0c69cad2017-08-21 12:12:51 -07003685 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003686 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003687}
3688
chaviw13fdc492017-06-27 12:40:18 -07003689status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003690 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003691 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003692{
chaviw13fdc492017-06-27 12:40:18 -07003693 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003694 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003695 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003696}
3697
Mathias Agopianac9fa422013-02-11 16:40:36 -08003698status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003699{
Robert Carr9524cb32017-02-13 11:32:32 -08003700 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003701 status_t err = NO_ERROR;
3702 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003703 if (l != nullptr) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003704 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003705 err = removeLayer(l);
3706 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3707 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003708 }
3709 return err;
3710}
3711
Mathias Agopian13127d82013-03-05 17:47:11 -08003712status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003713{
Mathias Agopian67106042013-03-14 19:18:13 -07003714 // called by ~LayerCleaner() when all references to the IBinder (handle)
3715 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003716 sp<Layer> l = layer.promote();
3717 if (l == nullptr) {
3718 // The layer has already been removed, carry on
3719 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003720 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003721 // If we have a parent, then we can continue to live as long as it does.
3722 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003723}
3724
Mathias Agopianb60314a2012-04-10 22:09:54 -07003725// ---------------------------------------------------------------------------
3726
Andy McFadden13a082e2012-08-24 10:16:42 -07003727void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003728 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003729 Vector<ComposerState> state;
3730 Vector<DisplayState> displays;
3731 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003732 d.what = DisplayState::eDisplayProjectionChanged |
3733 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003734 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003735 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003736 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003737 d.frame.makeInvalid();
3738 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003739 d.width = 0;
3740 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003741 displays.add(d);
3742 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003743 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3744 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003745
David Sodman105b7dc2017-11-04 20:28:14 -07003746 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003747 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003748 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003749
Brian Andersond0010582017-03-07 13:20:31 -08003750 // Use phase of 0 since phase is not known.
3751 // Use latency of 0, which will snap to the ideal latency.
3752 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003753}
3754
3755void SurfaceFlinger::initializeDisplays() {
3756 class MessageScreenInitialized : public MessageBase {
3757 SurfaceFlinger* flinger;
3758 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003759 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003760 virtual bool handler() {
3761 flinger->onInitializeDisplays();
3762 return true;
3763 }
3764 };
3765 sp<MessageBase> msg = new MessageScreenInitialized(this);
3766 postMessageAsync(msg); // we may be called from main thread, use async message
3767}
3768
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003769void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003770 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003771 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3772 this);
3773 int32_t type = hw->getDisplayType();
3774 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003775
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003776 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003777 return;
3778 }
3779
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003780 hw->setPowerMode(mode);
3781 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3782 ALOGW("Trying to set power mode for virtual display");
3783 return;
3784 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003785
Lloyd Pique4d234852018-01-22 17:21:36 -08003786 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003787 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003788 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3789 if (idx < 0) {
3790 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3791 return;
3792 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003793 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003794 }
3795
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003796 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003797 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003798 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003799 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3800 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003801 // FIXME: eventthread only knows about the main display right now
3802 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003803 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003804 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003805
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003806 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003807 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003808 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003809
3810 struct sched_param param = {0};
3811 param.sched_priority = 1;
3812 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3813 ALOGW("Couldn't set SCHED_FIFO on display on");
3814 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003815 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003816 // Turn off the display
3817 struct sched_param param = {0};
3818 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3819 ALOGW("Couldn't set SCHED_OTHER on display off");
3820 }
3821
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003822 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3823 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003824 disableHardwareVsync(true); // also cancels any in-progress resync
3825
Mathias Agopiancde87a32012-09-13 14:09:01 -07003826 // FIXME: eventthread only knows about the main display right now
3827 mEventThread->onScreenReleased();
3828 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003829
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003830 getHwComposer().setPowerMode(type, mode);
3831 mVisibleRegionsDirty = true;
3832 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003833 } else if (mode == HWC_POWER_MODE_DOZE ||
3834 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003835 // Update display while dozing
3836 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003837 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3838 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003839 // FIXME: eventthread only knows about the main display right now
3840 mEventThread->onScreenAcquired();
3841 resyncToHardwareVsync(true);
3842 }
3843 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3844 // Leave display going to doze
3845 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3846 disableHardwareVsync(true); // also cancels any in-progress resync
3847 // FIXME: eventthread only knows about the main display right now
3848 mEventThread->onScreenReleased();
3849 }
3850 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003851 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003852 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003853 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003854 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003855 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003856}
3857
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003858void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3859 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003860 SurfaceFlinger& mFlinger;
3861 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003862 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003863 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003864 MessageSetPowerMode(SurfaceFlinger& flinger,
3865 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3866 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003867 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003868 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003869 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003870 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003871 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003872 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003873 ALOGW("Attempt to set power mode = %d for virtual display",
3874 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003875 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003876 mFlinger.setPowerModeInternal(
3877 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003878 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003879 return true;
3880 }
3881 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003882 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003883 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003884}
3885
3886// ---------------------------------------------------------------------------
3887
Lloyd Pique755e3192018-01-31 16:46:15 -08003888status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3889 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003890 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003891
Mathias Agopianbd115332013-04-18 16:41:04 -07003892 IPCThreadState* ipc = IPCThreadState::self();
3893 const int pid = ipc->getCallingPid();
3894 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003895
Mathias Agopianbd115332013-04-18 16:41:04 -07003896 if ((uid != AID_SHELL) &&
3897 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003898 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003899 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003900 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003901 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003902 // (this would indicate SF is stuck, but we want to be able to
3903 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003904 status_t err = mStateLock.timedLock(s2ns(1));
3905 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003906 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003907 result.appendFormat(
3908 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3909 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003910 }
3911
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003912 bool dumpAll = true;
3913 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003914 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003915
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003916 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003917 if ((index < numArgs) &&
3918 (args[index] == String16("--list"))) {
3919 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003920 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003921 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003922 }
3923
3924 if ((index < numArgs) &&
3925 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003926 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003927 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003928 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003929 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003930
3931 if ((index < numArgs) &&
3932 (args[index] == String16("--latency-clear"))) {
3933 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003934 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003935 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003936 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003937
3938 if ((index < numArgs) &&
3939 (args[index] == String16("--dispsync"))) {
3940 index++;
3941 mPrimaryDispSync.dump(result);
3942 dumpAll = false;
3943 }
Dan Stozab90cf072015-03-05 11:05:59 -08003944
3945 if ((index < numArgs) &&
3946 (args[index] == String16("--static-screen"))) {
3947 index++;
3948 dumpStaticScreenStats(result);
3949 dumpAll = false;
3950 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003951
3952 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003953 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003954 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003955 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003956 dumpAll = false;
3957 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003958
3959 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3960 index++;
3961 dumpWideColorInfo(result);
3962 dumpAll = false;
3963 }
Yiwei Zhang068e31b2018-02-21 13:02:45 -08003964
3965 if ((index < numArgs) &&
3966 (args[index] == String16("--enable-layer-stats"))) {
3967 index++;
3968 mLayerStats.enable();
3969 dumpAll = false;
3970 }
3971
3972 if ((index < numArgs) &&
3973 (args[index] == String16("--disable-layer-stats"))) {
3974 index++;
3975 mLayerStats.disable();
3976 dumpAll = false;
3977 }
3978
3979 if ((index < numArgs) &&
3980 (args[index] == String16("--clear-layer-stats"))) {
3981 index++;
3982 mLayerStats.clear();
3983 dumpAll = false;
3984 }
3985
3986 if ((index < numArgs) &&
3987 (args[index] == String16("--dump-layer-stats"))) {
3988 index++;
3989 mLayerStats.dump(result);
3990 dumpAll = false;
3991 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -07003992
3993 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3994 index++;
3995 mTimeStats.parseArgs(asProto, args, index, result);
3996 dumpAll = false;
3997 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003998 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003999
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004000 if (dumpAll) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -07004001 if (asProto) {
4002 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4003 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4004 } else {
4005 dumpAllLocked(args, index, result);
4006 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004007 }
4008
Mathias Agopian9795c422009-08-26 16:36:26 -07004009 if (locked) {
4010 mStateLock.unlock();
4011 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004012 }
4013 write(fd, result.string(), result.size());
4014 return NO_ERROR;
4015}
4016
Dan Stozac7014012014-02-14 15:03:43 -08004017void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4018 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004019{
Robert Carr2047fae2016-11-28 14:09:09 -08004020 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004021 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004022 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004023}
4024
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004025void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004026 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004027{
4028 String8 name;
4029 if (index < args.size()) {
4030 name = String8(args[index]);
4031 index++;
4032 }
4033
David Sodman105b7dc2017-11-04 20:28:14 -07004034 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004035 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08004036 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004037
4038 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004039 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004040 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004041 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004042 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004043 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004044 }
Robert Carr2047fae2016-11-28 14:09:09 -08004045 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004046 }
4047}
4048
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004049void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004050 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004051{
4052 String8 name;
4053 if (index < args.size()) {
4054 name = String8(args[index]);
4055 index++;
4056 }
4057
Robert Carr2047fae2016-11-28 14:09:09 -08004058 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004059 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004060 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004061 }
Robert Carr2047fae2016-11-28 14:09:09 -08004062 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004063
Svetoslavd85084b2014-03-20 10:28:31 -07004064 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004065}
4066
Jamie Gennis6547ff42013-07-16 20:12:42 -07004067// This should only be called from the main thread. Otherwise it would need
4068// the lock and should use mCurrentState rather than mDrawingState.
4069void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004070 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004071 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004072 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004073
4074 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4075}
4076
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004077void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004078{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004079 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004080
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004081 if (isLayerTripleBufferingDisabled())
4082 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004083
4084 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004085 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004086 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004087 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004088 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4089 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004090 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004091}
4092
Dan Stozab90cf072015-03-05 11:05:59 -08004093void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4094{
4095 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004096 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4097 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004098 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004099 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004100 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4101 b + 1, bucketTimeSec, percent);
4102 }
David Sodman4a36e932017-11-07 14:29:47 -08004103 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004104 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004105 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004106 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004107 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004108}
4109
Dan Stozae77c7662016-05-13 11:37:28 -07004110void SurfaceFlinger::recordBufferingStats(const char* layerName,
4111 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004112 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4113 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004114 for (const auto& segment : history) {
4115 if (!segment.usedThirdBuffer) {
4116 stats.twoBufferTime += segment.totalTime;
4117 }
4118 if (segment.occupancyAverage < 1.0f) {
4119 stats.doubleBufferedTime += segment.totalTime;
4120 } else if (segment.occupancyAverage < 2.0f) {
4121 stats.tripleBufferedTime += segment.totalTime;
4122 }
4123 ++stats.numSegments;
4124 stats.totalTime += segment.totalTime;
4125 }
4126}
4127
Brian Andersond6927fb2016-07-23 23:37:30 -07004128void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4129 result.appendFormat("Layer frame timestamps:\n");
4130
4131 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4132 const size_t count = currentLayers.size();
4133 for (size_t i=0 ; i<count ; i++) {
4134 currentLayers[i]->dumpFrameEvents(result);
4135 }
4136}
4137
Dan Stozae77c7662016-05-13 11:37:28 -07004138void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4139 result.append("Buffering stats:\n");
4140 result.append(" [Layer name] <Active time> <Two buffer> "
4141 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004142 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004143 typedef std::tuple<std::string, float, float, float> BufferTuple;
4144 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004145 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004146 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004147 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004148 if (stats.numSegments == 0) {
4149 continue;
4150 }
4151 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4152 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4153 stats.totalTime;
4154 float doubleBufferRatio = static_cast<float>(
4155 stats.doubleBufferedTime) / stats.totalTime;
4156 float tripleBufferRatio = static_cast<float>(
4157 stats.tripleBufferedTime) / stats.totalTime;
4158 sorted.insert({activeTime, {name, twoBufferRatio,
4159 doubleBufferRatio, tripleBufferRatio}});
4160 }
4161 for (const auto& sortedPair : sorted) {
4162 float activeTime = sortedPair.first;
4163 const BufferTuple& values = sortedPair.second;
4164 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4165 std::get<0>(values).c_str(), activeTime,
4166 std::get<1>(values), std::get<2>(values),
4167 std::get<3>(values));
4168 }
4169 result.append("\n");
4170}
4171
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004172void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4173 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004174 result.appendFormat("DisplayColorSetting: %d\n", mDisplayColorSetting);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004175
4176 // TODO: print out if wide-color mode is active or not
4177
4178 for (size_t d = 0; d < mDisplays.size(); d++) {
4179 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4180 int32_t hwcId = displayDevice->getHwcDisplayId();
4181 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4182 continue;
4183 }
4184
4185 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004186 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004187 for (auto&& mode : modes) {
4188 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4189 }
4190
Peiyong Lina52f0292018-03-14 17:26:31 -07004191 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004192 result.appendFormat(" Current color mode: %s (%d)\n",
4193 decodeColorMode(currentMode).c_str(), currentMode);
4194 }
4195 result.append("\n");
4196}
4197
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004198LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004199 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004200 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4201 const State& state = useDrawing ? mDrawingState : mCurrentState;
4202 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004203 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004204 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004205 });
4206
4207 return layersProto;
4208}
4209
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004210LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4211 LayersProto layersProto;
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004212 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004213
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004214 SizeProto* resolution = layersProto.mutable_resolution();
4215 resolution->set_w(displayDevice->getWidth());
4216 resolution->set_h(displayDevice->getHeight());
4217
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004218 layersProto.set_color_mode(decodeColorMode(displayDevice->getActiveColorMode()));
4219 layersProto.set_color_transform(decodeColorTransform(displayDevice->getColorTransform()));
4220 layersProto.set_global_transform(
4221 static_cast<int32_t>(displayDevice->getOrientationTransform()));
4222
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004223 mDrawingState.traverseInZOrder([&](Layer* layer) {
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004224 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004225 LayerProto* layerProto = layersProto.add_layers();
4226 layer->writeToProto(layerProto, hwcId);
4227 }
4228 });
4229
4230 return layersProto;
4231}
4232
Mathias Agopian74d211a2013-04-22 16:55:35 +02004233void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4234 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004235{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004236 bool colorize = false;
4237 if (index < args.size()
4238 && (args[index] == String16("--color"))) {
4239 colorize = true;
4240 index++;
4241 }
4242
4243 Colorizer colorizer(colorize);
4244
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004245 // figure out if we're stuck somewhere
4246 const nsecs_t now = systemTime();
4247 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4248 const nsecs_t inTransaction(mDebugInTransaction);
4249 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4250 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4251
4252 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004253 * Dump library configuration.
4254 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004255
4256 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004257 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004258 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004259 appendSfConfigString(result);
4260 appendUiConfigString(result);
4261 appendGuiConfigString(result);
4262 result.append("\n");
4263
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004264 result.append("\nWide-Color information:\n");
4265 dumpWideColorInfo(result);
4266
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004267 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004268 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004269 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004270 result.append(SyncFeatures::getInstance().toString());
4271 result.append("\n");
4272
David Sodman105b7dc2017-11-04 20:28:14 -07004273 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004274
Andy McFadden41d67d72014-04-25 16:58:34 -07004275 colorizer.bold(result);
4276 result.append("DispSync configuration: ");
4277 colorizer.reset(result);
Dan Stoza2713c302018-03-28 17:07:36 -07004278 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, early sf phase %" PRId64
4279 " ns, present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4280 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, mVsyncModulator.getEarlyPhaseOffset(),
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004281 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004282 result.append("\n");
4283
Dan Stozab90cf072015-03-05 11:05:59 -08004284 // Dump static screen stats
4285 result.append("\n");
4286 dumpStaticScreenStats(result);
4287 result.append("\n");
4288
Dan Stozae77c7662016-05-13 11:37:28 -07004289 dumpBufferingStats(result);
4290
Andy McFadden4803b742012-09-24 19:07:20 -07004291 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004292 * Dump the visible layer list
4293 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004294 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004295 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004296 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4297 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004298 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004299
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004300 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004301 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7794ec12018-03-14 13:28:39 -07004302 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004303 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004304
4305 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004306 * Dump Display state
4307 */
4308
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004309 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004310 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004311 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004312 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4313 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004314 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004315 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004316 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004317
4318 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004319 * Dump SurfaceFlinger global state
4320 */
4321
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004322 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004323 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004324 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004325
Mathias Agopian888c8222012-08-04 21:10:38 -07004326 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004327 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004328
David Sodmanbc815282017-11-05 18:57:52 -08004329 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004330
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004331 if (hw) {
4332 hw->undefinedRegion.dump(result, "undefinedRegion");
4333 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4334 hw->getOrientation(), hw->isDisplayOn());
4335 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004336 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004337 " last eglSwapBuffers() time: %f us\n"
4338 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004339 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004340 " refresh-rate : %f fps\n"
4341 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004342 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004343 " gpu_to_cpu_unsupported : %d\n"
4344 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004345 mLastSwapBufferTime/1000.0,
4346 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004347 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004348 1e9 / activeConfig->getVsyncPeriod(),
4349 activeConfig->getDpiX(),
4350 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004351 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004352
Mathias Agopian74d211a2013-04-22 16:55:35 +02004353 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004354 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004355
Mathias Agopian74d211a2013-04-22 16:55:35 +02004356 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004357 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004358
4359 /*
4360 * VSYNC state
4361 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004362 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004363 result.append("\n");
4364
4365 /*
4366 * HWC layer minidump
4367 */
4368 for (size_t d = 0; d < mDisplays.size(); d++) {
4369 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4370 int32_t hwcId = displayDevice->getHwcDisplayId();
4371 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4372 continue;
4373 }
4374
4375 result.appendFormat("Display %d HWC layers:\n", hwcId);
4376 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004377 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004378 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004379 });
Dan Stozae22aec72016-08-01 13:20:59 -07004380 result.append("\n");
4381 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004382
4383 /*
4384 * Dump HWComposer state
4385 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004386 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004387 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004388 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004389 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004390 result.appendFormat(" h/w composer %s\n",
4391 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004392 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004393
4394 /*
4395 * Dump gralloc state
4396 */
4397 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4398 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004399
4400 /*
4401 * Dump VrFlinger state if in use.
4402 */
4403 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4404 result.append("VrFlinger state:\n");
4405 result.append(mVrFlinger->Dump().c_str());
4406 result.append("\n");
4407 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004408}
4409
Mathias Agopian13127d82013-03-05 17:47:11 -08004410const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004411SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004412 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004413 wp<IBinder> dpy;
4414 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4415 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4416 dpy = mDisplays.keyAt(i);
4417 break;
4418 }
4419 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004420 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004421 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4422 // Just use the primary display so we have something to return
4423 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4424 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004425 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004426}
4427
Keun young Park63f165f2012-08-31 10:53:36 -07004428bool SurfaceFlinger::startDdmConnection()
4429{
4430 void* libddmconnection_dso =
4431 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4432 if (!libddmconnection_dso) {
4433 return false;
4434 }
4435 void (*DdmConnection_start)(const char* name);
4436 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004437 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004438 if (!DdmConnection_start) {
4439 dlclose(libddmconnection_dso);
4440 return false;
4441 }
4442 (*DdmConnection_start)(getServiceName());
4443 return true;
4444}
4445
Chia-I Wu28f320b2018-05-03 11:02:56 -07004446void SurfaceFlinger::updateColorMatrixLocked() {
4447 mat4 colorMatrix;
4448 if (mGlobalSaturationFactor != 1.0f) {
4449 // Rec.709 luma coefficients
4450 float3 luminance{0.213f, 0.715f, 0.072f};
4451 luminance *= 1.0f - mGlobalSaturationFactor;
4452 mat4 saturationMatrix = mat4(
4453 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4454 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4455 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4456 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4457 );
4458 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4459 } else {
4460 colorMatrix = mClientColorMatrix * mDaltonizer();
4461 }
4462
4463 if (mCurrentState.colorMatrix != colorMatrix) {
4464 mCurrentState.colorMatrix = colorMatrix;
4465 mCurrentState.colorMatrixChanged = true;
4466 setTransactionFlags(eTransactionNeeded);
4467 }
4468}
4469
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004470status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004471 switch (code) {
4472 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004473 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004474 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004475 case CLEAR_ANIMATION_FRAME_STATS:
4476 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004477 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004478 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004479 case ENABLE_VSYNC_INJECTIONS:
4480 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004481 {
4482 // codes that require permission check
4483 IPCThreadState* ipc = IPCThreadState::self();
4484 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004485 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004486 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004487 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004488 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004489 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004490 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004491 break;
4492 }
Robert Carr1db73f62016-12-21 12:58:51 -08004493 /*
4494 * Calling setTransactionState is safe, because you need to have been
4495 * granted a reference to Client* and Handle* to do anything with it.
4496 *
4497 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4498 */
4499 case SET_TRANSACTION_STATE:
4500 case CREATE_SCOPED_CONNECTION:
4501 {
4502 return OK;
4503 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004504 case CAPTURE_SCREEN:
4505 {
4506 // codes that require permission check
4507 IPCThreadState* ipc = IPCThreadState::self();
4508 const int pid = ipc->getCallingPid();
4509 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004510 if ((uid != AID_GRAPHICS) &&
4511 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004512 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004513 return PERMISSION_DENIED;
4514 }
4515 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004516 }
chaviwa76b2712017-09-20 12:02:26 -07004517 case CAPTURE_LAYERS: {
4518 IPCThreadState* ipc = IPCThreadState::self();
4519 const int pid = ipc->getCallingPid();
4520 const int uid = ipc->getCallingUid();
4521 if ((uid != AID_GRAPHICS) &&
4522 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4523 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4524 return PERMISSION_DENIED;
4525 }
4526 break;
4527 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004528 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004529 return OK;
4530}
4531
4532status_t SurfaceFlinger::onTransact(
4533 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4534{
4535 status_t credentialCheck = CheckTransactCodeCredentials(code);
4536 if (credentialCheck != OK) {
4537 return credentialCheck;
4538 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004539
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004540 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4541 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004542 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004543 IPCThreadState* ipc = IPCThreadState::self();
4544 const int uid = ipc->getCallingUid();
4545 if (CC_UNLIKELY(uid != AID_SYSTEM
4546 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004547 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004548 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004549 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004550 return PERMISSION_DENIED;
4551 }
4552 int n;
4553 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004554 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004555 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004556 return NO_ERROR;
4557 case 1002: // SHOW_UPDATES
4558 n = data.readInt32();
4559 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004560 invalidateHwcGeometry();
4561 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004562 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004563 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004564 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004565 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004566 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004567 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004568 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004569 setTransactionFlags(
4570 eTransactionNeeded|
4571 eDisplayTransactionNeeded|
4572 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004573 return NO_ERROR;
4574 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004575 case 1006:{ // send empty update
4576 signalRefresh();
4577 return NO_ERROR;
4578 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004579 case 1008: // toggle use of hw composer
4580 n = data.readInt32();
4581 mDebugDisableHWC = n ? 1 : 0;
4582 invalidateHwcGeometry();
4583 repaintEverything();
4584 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004585 case 1009: // toggle use of transform hint
4586 n = data.readInt32();
4587 mDebugDisableTransformHint = n ? 1 : 0;
4588 invalidateHwcGeometry();
4589 repaintEverything();
4590 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004591 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004592 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004593 reply->writeInt32(0);
4594 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004595 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004596 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004597 return NO_ERROR;
4598 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004599 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004600 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004601 return NO_ERROR;
4602 }
4603 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004604 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004605 // daltonize
4606 n = data.readInt32();
4607 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004608 case 1:
4609 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4610 break;
4611 case 2:
4612 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4613 break;
4614 case 3:
4615 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4616 break;
4617 default:
4618 mDaltonizer.setType(ColorBlindnessType::None);
4619 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004620 }
4621 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004622 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004623 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004624 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004625 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004626
4627 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004628 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004629 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004630 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004631 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004632 // apply a color matrix
4633 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004634 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004635 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004636 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004637 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004638 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004639 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004640 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004641 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004642 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004643 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004644
4645 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4646 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004647 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004648 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4649 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4650 }
4651
Chia-I Wu28f320b2018-05-03 11:02:56 -07004652 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004653 return NO_ERROR;
4654 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004655 // This is an experimental interface
4656 // Needs to be shifted to proper binder interface when we productize
4657 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004658 n = data.readInt32();
4659 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004660 return NO_ERROR;
4661 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004662 case 1017: {
4663 n = data.readInt32();
4664 mForceFullDamage = static_cast<bool>(n);
4665 return NO_ERROR;
4666 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004667 case 1018: { // Modify Choreographer's phase offset
4668 n = data.readInt32();
4669 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4670 return NO_ERROR;
4671 }
4672 case 1019: { // Modify SurfaceFlinger's phase offset
4673 n = data.readInt32();
4674 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4675 return NO_ERROR;
4676 }
Irvel468051e2016-06-13 16:44:44 -07004677 case 1020: { // Layer updates interceptor
4678 n = data.readInt32();
4679 if (n) {
4680 ALOGV("Interceptor enabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004681 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004682 }
4683 else{
4684 ALOGV("Interceptor disabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004685 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004686 }
4687 return NO_ERROR;
4688 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004689 case 1021: { // Disable HWC virtual displays
4690 n = data.readInt32();
4691 mUseHwcVirtualDisplays = !n;
4692 return NO_ERROR;
4693 }
Romain Guy0147a172017-06-01 13:53:56 -07004694 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004695 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004696 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004697
Chia-I Wu28f320b2018-05-03 11:02:56 -07004698 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004699 return NO_ERROR;
4700 }
Romain Guy54f154a2017-10-24 21:40:32 +01004701 case 1023: { // Set native mode
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004702 int32_t value = data.readInt32();
4703 if (value > 2) {
4704 return BAD_VALUE;
4705 }
4706 if (value == 2 && !mBuiltinDisplaySupportsEnhance) {
4707 return BAD_VALUE;
4708 }
Romain Guy54f154a2017-10-24 21:40:32 +01004709
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004710 mDisplayColorSetting = toDisplayColorSetting(value);
Romain Guy54f154a2017-10-24 21:40:32 +01004711 invalidateHwcGeometry();
4712 repaintEverything();
4713 return NO_ERROR;
4714 }
4715 case 1024: { // Is wide color gamut rendering/color management supported?
4716 reply->writeBool(hasWideColorDisplay);
4717 return NO_ERROR;
4718 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004719 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004720 n = data.readInt32();
4721 if (n) {
4722 ALOGV("LayerTracing enabled");
4723 mTracing.enable();
4724 doTracing("tracing.enable");
4725 reply->writeInt32(NO_ERROR);
4726 } else {
4727 ALOGV("LayerTracing disabled");
4728 status_t err = mTracing.disable();
4729 reply->writeInt32(err);
4730 }
4731 return NO_ERROR;
4732 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004733 case 1026: { // Get layer tracing status
4734 reply->writeBool(mTracing.isEnabled());
4735 return NO_ERROR;
4736 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004737 // Is a DisplayColorSetting supported?
4738 case 1027: {
4739 int32_t value = data.readInt32();
4740 switch (value) {
4741 case 0:
4742 reply->writeBool(hasWideColorDisplay);
4743 return NO_ERROR;
4744 case 1:
4745 reply->writeBool(true);
4746 return NO_ERROR;
4747 case 2:
4748 reply->writeBool(mBuiltinDisplaySupportsEnhance);
4749 return NO_ERROR;
4750 default:
4751 return BAD_VALUE;
4752 }
4753 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004754 }
4755 }
4756 return err;
4757}
4758
Steven Thomas6d8110b2017-08-31 18:24:21 -07004759void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004760 android_atomic_or(1, &mRepaintEverything);
4761 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004762}
4763
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004764// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4765class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004766public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004767 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4768 ~WindowDisconnector() {
4769 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004770 }
4771
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004772private:
4773 ANativeWindow* mWindow;
4774 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004775};
4776
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004777status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4778 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4779 int32_t minLayerZ, int32_t maxLayerZ,
4780 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004781 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004782 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004783
chaviwa76b2712017-09-20 12:02:26 -07004784 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4785
4786 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004787 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4788
chaviwa76b2712017-09-20 12:02:26 -07004789 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4790
4791 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4792 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004793 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004794}
4795
4796status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004797 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004798 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004799 ATRACE_CALL();
4800
4801 class LayerRenderArea : public RenderArea {
4802 public:
Robert Carr578038f2018-03-09 12:25:24 -08004803 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4804 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004805 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004806 mLayer(layer),
4807 mCrop(crop),
4808 mFlinger(flinger),
4809 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004810 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004811 Rect getBounds() const override {
4812 const Layer::State& layerState(mLayer->getDrawingState());
4813 return Rect(layerState.active.w, layerState.active.h);
4814 }
4815 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4816 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4817 bool isSecure() const override { return false; }
4818 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004819 Rect getSourceCrop() const override {
4820 if (mCrop.isEmpty()) {
4821 return getBounds();
4822 } else {
4823 return mCrop;
4824 }
4825 }
Robert Carr578038f2018-03-09 12:25:24 -08004826 class ReparentForDrawing {
4827 public:
4828 const sp<Layer>& oldParent;
4829 const sp<Layer>& newParent;
4830
4831 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4832 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004833 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004834 }
Robert Carr15eae092018-03-23 13:43:53 -07004835 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004836 };
4837
4838 void render(std::function<void()> drawLayers) override {
4839 if (!mChildrenOnly) {
4840 mTransform = mLayer->getTransform().inverse();
4841 drawLayers();
4842 } else {
4843 Rect bounds = getBounds();
4844 screenshotParentLayer =
4845 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4846 bounds.getWidth(), bounds.getHeight(), 0);
4847
4848 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4849 drawLayers();
4850 }
4851 }
chaviwa76b2712017-09-20 12:02:26 -07004852
chaviwa76b2712017-09-20 12:02:26 -07004853 private:
chaviw7206d492017-11-10 16:16:12 -08004854 const sp<Layer> mLayer;
4855 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004856
4857 // In the "childrenOnly" case we reparent the children to a screenshot
4858 // layer which has no properties set and which does not draw.
4859 sp<ContainerLayer> screenshotParentLayer;
4860 Transform mTransform;
4861
4862 SurfaceFlinger* mFlinger;
4863 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004864 };
4865
4866 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4867 auto parent = layerHandle->owner.promote();
4868
chaviw7206d492017-11-10 16:16:12 -08004869 if (parent == nullptr || parent->isPendingRemoval()) {
4870 ALOGE("captureLayers called with a removed parent");
4871 return NAME_NOT_FOUND;
4872 }
4873
Robert Carr578038f2018-03-09 12:25:24 -08004874 const int uid = IPCThreadState::self()->getCallingUid();
4875 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4876 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4877 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4878 return PERMISSION_DENIED;
4879 }
4880
chaviw7206d492017-11-10 16:16:12 -08004881 Rect crop(sourceCrop);
4882 if (sourceCrop.width() <= 0) {
4883 crop.left = 0;
4884 crop.right = parent->getCurrentState().active.w;
4885 }
4886
4887 if (sourceCrop.height() <= 0) {
4888 crop.top = 0;
4889 crop.bottom = parent->getCurrentState().active.h;
4890 }
4891
4892 int32_t reqWidth = crop.width() * frameScale;
4893 int32_t reqHeight = crop.height() * frameScale;
4894
Robert Carr578038f2018-03-09 12:25:24 -08004895 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004896
Robert Carr578038f2018-03-09 12:25:24 -08004897 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004898 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4899 if (!layer->isVisible()) {
4900 return;
Robert Carr578038f2018-03-09 12:25:24 -08004901 } else if (childrenOnly && layer == parent.get()) {
4902 return;
chaviwa76b2712017-09-20 12:02:26 -07004903 }
4904 visitor(layer);
4905 });
4906 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004907 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004908}
4909
4910status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4911 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004912 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004913 bool useIdentityTransform) {
4914 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004915
chaviwa76b2712017-09-20 12:02:26 -07004916 renderArea.updateDimensions();
4917
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004918 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4919 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4920 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4921 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004922
4923 // This mutex protects syncFd and captureResult for communication of the return values from the
4924 // main thread back to this Binder thread
4925 std::mutex captureMutex;
4926 std::condition_variable captureCondition;
4927 std::unique_lock<std::mutex> captureLock(captureMutex);
4928 int syncFd = -1;
4929 std::optional<status_t> captureResult;
4930
Robert Carr03480e22018-01-04 16:02:06 -08004931 const int uid = IPCThreadState::self()->getCallingUid();
4932 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4933
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004934 sp<LambdaMessage> message = new LambdaMessage([&]() {
4935 // If there is a refresh pending, bug out early and tell the binder thread to try again
4936 // after the refresh.
4937 if (mRefreshPending) {
4938 ATRACE_NAME("Skipping screenshot for now");
4939 std::unique_lock<std::mutex> captureLock(captureMutex);
4940 captureResult = std::make_optional<status_t>(EAGAIN);
4941 captureCondition.notify_one();
4942 return;
4943 }
4944
4945 status_t result = NO_ERROR;
4946 int fd = -1;
4947 {
4948 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004949 renderArea.render([&]() {
4950 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4951 useIdentityTransform, forSystem, &fd);
4952 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004953 }
4954
4955 {
4956 std::unique_lock<std::mutex> captureLock(captureMutex);
4957 syncFd = fd;
4958 captureResult = std::make_optional<status_t>(result);
4959 captureCondition.notify_one();
4960 }
4961 });
4962
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004963 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004964 if (result == NO_ERROR) {
4965 captureCondition.wait(captureLock, [&]() { return captureResult; });
4966 while (*captureResult == EAGAIN) {
4967 captureResult.reset();
4968 result = postMessageAsync(message);
4969 if (result != NO_ERROR) {
4970 return result;
4971 }
4972 captureCondition.wait(captureLock, [&]() { return captureResult; });
4973 }
4974 result = *captureResult;
4975 }
4976
4977 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004978 sync_wait(syncFd, -1);
4979 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004980 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004981
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004982 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004983}
4984
chaviwa76b2712017-09-20 12:02:26 -07004985void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4986 TraverseLayersFunction traverseLayers, bool yswap,
4987 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004988 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004989
Lloyd Pique144e1162017-12-20 16:44:52 -08004990 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004991
4992 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004993 const auto raWidth = renderArea.getWidth();
4994 const auto raHeight = renderArea.getHeight();
4995
4996 const auto reqWidth = renderArea.getReqWidth();
4997 const auto reqHeight = renderArea.getReqHeight();
4998 Rect sourceCrop = renderArea.getSourceCrop();
4999
5000 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5001 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005002
Dan Stozac1879002014-05-22 15:59:05 -07005003 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005004 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005005 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005006 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07005007 }
5008
5009 // ensure that sourceCrop is inside screen
5010 if (sourceCrop.left < 0) {
5011 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5012 }
chaviwa76b2712017-09-20 12:02:26 -07005013 if (sourceCrop.right > raWidth) {
5014 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005015 }
5016 if (sourceCrop.top < 0) {
5017 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5018 }
chaviwa76b2712017-09-20 12:02:26 -07005019 if (sourceCrop.bottom > raHeight) {
5020 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005021 }
5022
Chia-I Wu36574d92018-05-16 10:54:36 -07005023 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5024 engine.setOutputDataSpace(Dataspace::SRGB);
5025 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005026
Mathias Agopian180f10d2013-04-10 22:55:41 -07005027 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005028 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005029
5030 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005031 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
5032 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07005033 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005034
chaviw50da5042018-04-09 13:49:37 -07005035 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005036 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005037 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005038
chaviwa76b2712017-09-20 12:02:26 -07005039 traverseLayers([&](Layer* layer) {
5040 if (filtering) layer->setFiltering(true);
5041 layer->draw(renderArea, useIdentityTransform);
5042 if (filtering) layer->setFiltering(false);
5043 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005044}
5045
chaviwa76b2712017-09-20 12:02:26 -07005046status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5047 TraverseLayersFunction traverseLayers,
5048 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005049 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005050 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005051 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005052 ATRACE_CALL();
5053
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005054 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005055
5056 traverseLayers([&](Layer* layer) {
5057 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5058 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005059
Robert Carr03480e22018-01-04 16:02:06 -08005060 // We allow the system server to take screenshots of secure layers for
5061 // use in situations like the Screen-rotation animation and place
5062 // the impetus on WindowManager to not persist them.
5063 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005064 ALOGW("FB is protected: PERMISSION_DENIED");
5065 return PERMISSION_DENIED;
5066 }
5067
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005068 // this binds the given EGLImage as a framebuffer for the
5069 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005070 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005071 if (bufferBond.getStatus() != NO_ERROR) {
5072 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005073 return INVALID_OPERATION;
5074 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005075
Dan Stozaabcda352017-06-01 14:37:39 -07005076 // this will in fact render into our dequeued buffer
5077 // via an FBO, which means we didn't have to create
5078 // an EGLSurface and therefore we're not
5079 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005080 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005081
Dan Stozaabcda352017-06-01 14:37:39 -07005082 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005083 getRenderEngine().finish();
5084 *outSyncFd = -1;
5085
chaviwa76b2712017-09-20 12:02:26 -07005086 const auto reqWidth = renderArea.getReqWidth();
5087 const auto reqHeight = renderArea.getReqHeight();
5088
Dan Stozaabcda352017-06-01 14:37:39 -07005089 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5090 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005091 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005092 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005093 } else {
5094 base::unique_fd syncFd = getRenderEngine().flush();
5095 if (syncFd < 0) {
5096 getRenderEngine().finish();
5097 }
5098 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005099 }
5100
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005101 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005102}
5103
Mathias Agopiand5556842013-09-19 17:08:37 -07005104void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005105 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005106 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005107 for (size_t y = 0; y < h; y++) {
5108 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5109 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005110 if (p[x] != 0xFF000000) return;
5111 }
5112 }
chaviwa76b2712017-09-20 12:02:26 -07005113 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005114
Robert Carr2047fae2016-11-28 14:09:09 -08005115 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005116 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005117 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005118 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5119 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5120 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5121 static_cast<float>(state.color.a));
5122 i++;
5123 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005124 }
5125}
5126
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005127// ---------------------------------------------------------------------------
5128
Dan Stoza412903f2017-04-27 13:42:17 -07005129void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5130 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005131}
5132
Dan Stoza412903f2017-04-27 13:42:17 -07005133void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5134 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005135}
5136
chaviwa76b2712017-09-20 12:02:26 -07005137void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
5138 int32_t maxLayerZ,
5139 const LayerVector::Visitor& visitor) {
5140 // We loop through the first level of layers without traversing,
5141 // as we need to interpret min/max layer Z in the top level Z space.
5142 for (const auto& layer : mDrawingState.layersSortedByZ) {
5143 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5144 continue;
5145 }
5146 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005147 // relative layers are traversed in Layer::traverseInZOrder
5148 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005149 continue;
5150 }
5151 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005152 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5153 return;
5154 }
chaviwa76b2712017-09-20 12:02:26 -07005155 if (!layer->isVisible()) {
5156 return;
5157 }
5158 visitor(layer);
5159 });
5160 }
5161}
5162
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005163}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005164
5165
5166#if defined(__gl_h_)
5167#error "don't include gl/gl.h in this file"
5168#endif
5169
5170#if defined(__gl2_h_)
5171#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005172#endif