blob: afa34d0c378ad9179af851f13186befd65c9381d [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"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070081#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070082#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070083#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070084#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080085
Mathias Agopianff2ed702013-09-01 21:36:12 -070086#include "Effects/Daltonizer.h"
87
Mathias Agopian875d8e12013-06-07 15:35:48 -070088#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070089#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070090
Jiyong Park4b20c2e2017-01-14 19:45:11 +090091#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090092#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090093
chaviw1d044282017-09-27 12:19:28 -070094#include <layerproto/LayerProtoParser.h>
95
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080096#define DISPLAY_COUNT 1
97
Mathias Agopianfee2b462013-07-03 12:34:01 -070098/*
99 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
100 * black pixels.
101 */
102#define DEBUG_SCREENSHOTS false
103
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800104namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700105
Jaesoo Lee43518572017-01-23 19:03:16 +0900106using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900107using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700108using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700109using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700110using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700111using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900112
Steven Thomasb02664d2017-07-26 18:48:28 -0700113namespace {
114class ConditionalLock {
115public:
116 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
117 if (lock) {
118 mMutex.lock();
119 }
120 }
121 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
122private:
123 Mutex& mMutex;
124 bool mLocked;
125};
126} // namespace anonymous
127
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800128// ---------------------------------------------------------------------------
129
Mathias Agopian99b49842011-06-27 16:05:52 -0700130const String16 sHardwareTest("android.permission.HARDWARE_TEST");
131const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
132const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
133const String16 sDump("android.permission.DUMP");
134
135// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800136int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
137int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700138int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700139bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800140uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800141bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800142bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800143int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800144// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600145bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700146
Kalle Raitaa099a242017-01-11 11:17:29 -0800147
148std::string getHwcServiceName() {
149 char value[PROPERTY_VALUE_MAX] = {};
150 property_get("debug.sf.hwc_service_name", value, "default");
151 ALOGI("Using HWComposer service: '%s'", value);
152 return std::string(value);
153}
154
155bool useTrebleTestingOverride() {
156 char value[PROPERTY_VALUE_MAX] = {};
157 property_get("debug.sf.treble_testing_override", value, "false");
158 ALOGI("Treble testing override: '%s'", value);
159 return std::string(value) == "true";
160}
161
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800162DisplayColorSetting toDisplayColorSetting(int value) {
163 switch(value) {
164 case 0:
165 return DisplayColorSetting::MANAGED;
166 case 1:
167 return DisplayColorSetting::UNMANAGED;
168 case 2:
169 return DisplayColorSetting::ENHANCED;
170 default:
171 return DisplayColorSetting::MANAGED;
172 }
173}
174
175std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
176 switch(displayColorSetting) {
177 case DisplayColorSetting::MANAGED:
178 return std::string("Natural Mode");
179 case DisplayColorSetting::UNMANAGED:
180 return std::string("Saturated Mode");
181 case DisplayColorSetting::ENHANCED:
182 return std::string("Auto Color Mode");
183 }
184 return std::string("Unknown Display Color Setting");
185}
186
Lloyd Pique99d3da52018-01-22 17:48:03 -0800187NativeWindowSurface::~NativeWindowSurface() = default;
188
189namespace impl {
190
191class NativeWindowSurface final : public android::NativeWindowSurface {
192public:
193 static std::unique_ptr<android::NativeWindowSurface> create(
194 const sp<IGraphicBufferProducer>& producer) {
195 return std::make_unique<NativeWindowSurface>(producer);
196 }
197
198 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
199 : surface(new Surface(producer, false)) {}
200
201 ~NativeWindowSurface() override = default;
202
203private:
204 sp<ANativeWindow> getNativeWindow() const override { return surface; }
205
206 void preallocateBuffers() override { surface->allocateBuffers(); }
207
208 sp<Surface> surface;
209};
210
211} // namespace impl
212
David Sodmanbc815282017-11-05 18:57:52 -0800213SurfaceFlingerBE::SurfaceFlingerBE()
214 : mHwcServiceName(getHwcServiceName()),
215 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800216 mFrameBuckets(),
217 mTotalTime(0),
218 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800219 mComposerSequenceId(0) {
220}
221
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800222SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800223 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800224 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700225 mTransactionPending(false),
226 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700227 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700228 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700229 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800230 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800231 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800232 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800233 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800234 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800235 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700236 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700237 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700238 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700239 mDebugInSwapBuffers(0),
240 mLastSwapBufferTime(0),
241 mDebugInTransaction(0),
242 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700243 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700244 mForceFullDamage(false),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000245 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700246 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700247 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800248 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800249 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700250 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800251 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800252 mCreateBufferQueue(&BufferQueue::createBufferQueue),
253 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800254
255SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800256 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800257
258 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
259 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
260
261 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
262 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
263
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800264 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
265 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800266
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700267 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
268 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
269
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700270 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
271 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
272
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800273 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
274 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
275
Steven Thomas050b2c82017-03-06 11:45:16 -0800276 // Vr flinger is only enabled on Daydream ready devices.
277 useVrFlinger = getBool< ISurfaceFlingerConfigs,
278 &ISurfaceFlingerConfigs::useVrFlinger>(false);
279
Fabien Sanglard1971b632017-03-10 14:50:03 -0800280 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
281 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
282
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600283 hasWideColorDisplay =
284 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
285
David Sodman99974d22017-11-28 12:04:33 -0800286 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700287
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800288 // debugging stuff...
289 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700290
Mathias Agopianb4b17302013-03-20 18:36:41 -0700291 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700292 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700293
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800294 property_get("debug.sf.showupdates", value, "0");
295 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700296
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700297 property_get("debug.sf.ddms", value, "0");
298 mDebugDDMS = atoi(value);
299 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700300 if (!startDdmConnection()) {
301 // start failed, and DDMS debugging not enabled
302 mDebugDDMS = 0;
303 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700304 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700305 ALOGI_IF(mDebugRegion, "showupdates enabled");
306 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700307
308 property_get("debug.sf.disable_backpressure", value, "0");
309 mPropagateBackpressure = !atoi(value);
310 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700311
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800312 property_get("debug.sf.enable_hwc_vds", value, "0");
313 mUseHwcVirtualDisplays = atoi(value);
314 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800315
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800316 property_get("ro.sf.disable_triple_buffer", value, "1");
317 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800318 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700319
Dan Stoza0a0158c2018-03-16 13:38:54 -0700320 // TODO (b/74616334): Reduce the default value once we isolate the leak
321 const size_t defaultListSize = 4 * MAX_LAYERS;
322 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
323 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
324
Dan Stoza84d619e2018-03-28 17:07:36 -0700325 property_get("debug.sf.early_phase_offset_ns", value, "0");
326 const int earlyWakeupOffsetOffsetNs = atoi(value);
327 ALOGI_IF(earlyWakeupOffsetOffsetNs != 0, "Enabling separate early offset");
328 mVsyncModulator.setPhaseOffsets(sfVsyncPhaseOffsetNs - earlyWakeupOffsetOffsetNs,
329 sfVsyncPhaseOffsetNs);
330
Romain Guy11d63f42017-07-20 12:47:14 -0700331 // We should be reading 'persist.sys.sf.color_saturation' here
332 // but since /data may be encrypted, we need to wait until after vold
333 // comes online to attempt to read the property. The property is
334 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800335
336 if (useTrebleTestingOverride()) {
337 // Without the override SurfaceFlinger cannot connect to HIDL
338 // services that are not listed in the manifests. Considered
339 // deriving the setting from the set service name, but it
340 // would be brittle if the name that's not 'default' is used
341 // for production purposes later on.
342 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
343 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800344}
345
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800346void SurfaceFlinger::onFirstRef()
347{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800348 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800349}
350
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800351SurfaceFlinger::~SurfaceFlinger()
352{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800353}
354
Dan Stozac7014012014-02-14 15:03:43 -0800355void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800356{
357 // the window manager died on us. prepare its eulogy.
358
Andy McFadden13a082e2012-08-24 10:16:42 -0700359 // restore initial conditions (default device unblank, etc)
360 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800361
362 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700363 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800364}
365
Robert Carr1db73f62016-12-21 12:58:51 -0800366static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700367 status_t err = client->initCheck();
368 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800369 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800370 }
Robert Carr1db73f62016-12-21 12:58:51 -0800371 return nullptr;
372}
373
374sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
375 return initClient(new Client(this));
376}
377
378sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
379 const sp<IGraphicBufferProducer>& gbp) {
380 if (authenticateSurfaceTexture(gbp) == false) {
381 return nullptr;
382 }
383 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
384 if (layer == nullptr) {
385 return nullptr;
386 }
387
388 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800389}
390
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700391sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
392 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700393{
394 class DisplayToken : public BBinder {
395 sp<SurfaceFlinger> flinger;
396 virtual ~DisplayToken() {
397 // no more references, this display must be terminated
398 Mutex::Autolock _l(flinger->mStateLock);
399 flinger->mCurrentState.displays.removeItem(this);
400 flinger->setTransactionFlags(eDisplayTransactionNeeded);
401 }
402 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700403 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700404 : flinger(flinger) {
405 }
406 };
407
408 sp<BBinder> token = new DisplayToken(this);
409
410 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700411 DisplayDeviceState info;
412 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700413 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700414 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700415 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800416 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700417 return token;
418}
419
Jesse Hall6c913be2013-08-08 12:15:49 -0700420void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
421 Mutex::Autolock _l(mStateLock);
422
423 ssize_t idx = mCurrentState.displays.indexOfKey(display);
424 if (idx < 0) {
425 ALOGW("destroyDisplay: invalid display token");
426 return;
427 }
428
429 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700430 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700431 ALOGE("destroyDisplay called for non-virtual display");
432 return;
433 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700434 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700435 mCurrentState.displays.removeItemsAt(idx);
436 setTransactionFlags(eDisplayTransactionNeeded);
437}
438
Mathias Agopiane57f2922012-08-09 16:29:12 -0700439sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700440 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700441 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800442 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700443 }
Jesse Hall692c7232012-11-08 15:41:56 -0800444 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700445}
446
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800447void SurfaceFlinger::bootFinished()
448{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700449 if (mStartPropertySetThread->join() != NO_ERROR) {
450 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800451 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800452 const nsecs_t now = systemTime();
453 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000454 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700455
456 // wait patiently for the window manager death
457 const String16 name("window");
458 sp<IBinder> window(defaultServiceManager()->getService(name));
459 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700460 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700461 }
462
Steven Thomas050b2c82017-03-06 11:45:16 -0800463 if (mVrFlinger) {
464 mVrFlinger->OnBootFinished();
465 }
466
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700467 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700468 // formerly we would just kill the process, but we now ask it to exit so it
469 // can choose where to stop the animation.
470 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700471
472 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
473 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
474 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700475
Thierry Strudel2924d012017-08-14 15:19:37 -0700476 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700477 readPersistentProperties();
478 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700479 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800480}
481
Mathias Agopian3f844832013-08-07 21:24:32 -0700482void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700483 class MessageDestroyGLTexture : public MessageBase {
Lloyd Pique144e1162017-12-20 16:44:52 -0800484 RE::RenderEngine& engine;
Mathias Agopian3f844832013-08-07 21:24:32 -0700485 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700486 public:
Lloyd Pique144e1162017-12-20 16:44:52 -0800487 MessageDestroyGLTexture(RE::RenderEngine& engine, uint32_t texture)
488 : engine(engine), texture(texture) {}
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700489 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700490 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700491 return true;
492 }
493 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700494 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700495}
496
Lloyd Piquee83f9312018-02-01 12:53:17 -0800497class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700498public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700499 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000500 const char* name) :
501 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700502 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700503 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000504 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
505 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700506 mDispSync(dispSync),
507 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700508 mVsyncMutex(),
509 mPhaseOffset(phaseOffset),
510 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700511
Lloyd Piquee83f9312018-02-01 12:53:17 -0800512 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700513
Lloyd Piquee83f9312018-02-01 12:53:17 -0800514 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700515 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700516 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000517 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700518 static_cast<DispSync::Callback*>(this));
519 if (err != NO_ERROR) {
520 ALOGE("error registering vsync callback: %s (%d)",
521 strerror(-err), err);
522 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700523 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700524 } else {
525 status_t err = mDispSync->removeEventListener(
526 static_cast<DispSync::Callback*>(this));
527 if (err != NO_ERROR) {
528 ALOGE("error unregistering vsync callback: %s (%d)",
529 strerror(-err), err);
530 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700531 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700532 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700533 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700534 }
535
Lloyd Piquee83f9312018-02-01 12:53:17 -0800536 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700537 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700538 mCallback = callback;
539 }
540
Lloyd Piquee83f9312018-02-01 12:53:17 -0800541 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700542 Mutex::Autolock lock(mVsyncMutex);
543
544 // Normalize phaseOffset to [0, period)
545 auto period = mDispSync->getPeriod();
546 phaseOffset %= period;
547 if (phaseOffset < 0) {
548 // If we're here, then phaseOffset is in (-period, 0). After this
549 // operation, it will be in (0, period)
550 phaseOffset += period;
551 }
552 mPhaseOffset = phaseOffset;
553
554 // If we're not enabled, we don't need to mess with the listeners
555 if (!mEnabled) {
556 return;
557 }
558
Dan Stoza84d619e2018-03-28 17:07:36 -0700559 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
560 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700561 if (err != NO_ERROR) {
Dan Stoza84d619e2018-03-28 17:07:36 -0700562 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700563 strerror(-err), err);
564 }
565 }
566
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700567private:
568 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800569 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700570 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700571 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700572 callback = mCallback;
573
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700574 if (mTraceVsync) {
575 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700576 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700577 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700578 }
579
Peiyong Lin566a3b42018-01-09 18:22:43 -0800580 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700581 callback->onVSyncEvent(when);
582 }
583 }
584
Tim Murray4a4e4a22016-04-19 16:29:23 +0000585 const char* const mName;
586
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700587 int mValue;
588
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700589 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700590 const String8 mVsyncOnLabel;
591 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700592
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700593 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700594
595 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800596 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700597
598 Mutex mVsyncMutex; // Protects the following
599 nsecs_t mPhaseOffset;
600 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700601};
602
Lloyd Piquee83f9312018-02-01 12:53:17 -0800603class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700604public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800605 InjectVSyncSource() = default;
606 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700607
Lloyd Piquee83f9312018-02-01 12:53:17 -0800608 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700609 std::lock_guard<std::mutex> lock(mCallbackMutex);
610 mCallback = callback;
611 }
612
Lloyd Piquee83f9312018-02-01 12:53:17 -0800613 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700614 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700615 if (mCallback) {
616 mCallback->onVSyncEvent(when);
617 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700618 }
619
Lloyd Piquee83f9312018-02-01 12:53:17 -0800620 void setVSyncEnabled(bool) override {}
621 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700622
623private:
624 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800625 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700626};
627
Wei Wangf9b05ee2017-07-19 20:59:39 -0700628// Do not call property_set on main thread which will be blocked by init
629// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700630void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700631 ALOGI( "SurfaceFlinger's main thread ready to run. "
632 "Initializing graphics H/W...");
633
Thierry Strudel2924d012017-08-14 15:19:37 -0700634 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900635
Steven Thomasb02664d2017-07-26 18:48:28 -0700636 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800637
Steven Thomasb02664d2017-07-26 18:48:28 -0700638 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800639 mEventThreadSource =
640 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
641 true, "app");
642 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(), *this, false,
643 "appEventThread");
644 mSfEventThreadSource =
645 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
646 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800647
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800648 mSFEventThread = std::make_unique<impl::EventThread>(mSfEventThreadSource.get(), *this, true,
649 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800650 mEventQueue->setEventThread(mSFEventThread.get());
Dan Stoza84d619e2018-03-28 17:07:36 -0700651 mVsyncModulator.setEventThread(mSFEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800652
Steven Thomasb02664d2017-07-26 18:48:28 -0700653 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800654 getBE().mRenderEngine =
655 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
656 hasWideColorDisplay
657 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
658 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800659 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700660
661 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
662 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800663 getBE().mHwc.reset(
664 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700665 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800666 // Process any initial hotplug and resulting display changes.
667 processDisplayHotplugEventsLocked();
668 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
669 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800670
Lloyd Piquefcd86612017-12-14 17:15:36 -0800671 // make the default display GLContext current so that we can create textures
672 // when creating Layers (which may happens before we render something)
673 getDefaultDisplayDeviceLocked()->makeCurrent();
674
Steven Thomas050b2c82017-03-06 11:45:16 -0800675 if (useVrFlinger) {
676 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700677 // This callback is called from the vr flinger dispatch thread. We
678 // need to call signalTransaction(), which requires holding
679 // mStateLock when we're not on the main thread. Acquiring
680 // mStateLock from the vr flinger dispatch thread might trigger a
681 // deadlock in surface flinger (see b/66916578), so post a message
682 // to be handled on the main thread instead.
683 sp<LambdaMessage> message = new LambdaMessage([=]() {
684 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
685 mVrFlingerRequestsDisplay = requestDisplay;
686 signalTransaction();
687 });
688 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800689 };
David Sodman105b7dc2017-11-04 20:28:14 -0700690 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
691 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800692 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800693 if (!mVrFlinger) {
694 ALOGE("Failed to start vrflinger");
695 }
696 }
697
Lloyd Pique379adc12018-01-22 17:31:47 -0800698 mEventControlThread = std::make_unique<impl::EventControlThread>(
699 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700700
Mathias Agopian92a979a2012-08-02 18:32:23 -0700701 // initialize our drawing state
702 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700703
Andy McFadden13a082e2012-08-24 10:16:42 -0700704 // set initial conditions (e.g. unblank default device)
705 initializeDisplays();
706
David Sodmanbc815282017-11-05 18:57:52 -0800707 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700708
Wei Wangf9b05ee2017-07-19 20:59:39 -0700709 // Inform native graphics APIs whether the present timestamp is supported:
710 if (getHwComposer().hasCapability(
711 HWC2::Capability::PresentFenceIsNotReliable)) {
712 mStartPropertySetThread = new StartPropertySetThread(false);
713 } else {
714 mStartPropertySetThread = new StartPropertySetThread(true);
715 }
716
717 if (mStartPropertySetThread->Start() != NO_ERROR) {
718 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800719 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800720
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800721 mLegacySrgbSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(HWC_DISPLAY_PRIMARY,
722 Dataspace::SRGB_LINEAR);
723
Dan Stoza9e56aa02015-11-02 13:00:03 -0800724 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700725}
726
Romain Guy11d63f42017-07-20 12:47:14 -0700727void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700728 Mutex::Autolock _l(mStateLock);
729
Romain Guy11d63f42017-07-20 12:47:14 -0700730 char value[PROPERTY_VALUE_MAX];
731
732 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800733 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700734 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800735 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100736
737 property_get("persist.sys.sf.native_mode", value, "0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800738 mDisplayColorSetting = toDisplayColorSetting(atoi(value));
739 ALOGV("Display Color Setting is set to %s.",
740 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Romain Guy11d63f42017-07-20 12:47:14 -0700741}
742
Mathias Agopiana67e4182012-06-19 17:26:12 -0700743void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800744 // Start boot animation service by setting a property mailbox
745 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700746 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800747 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700748 if (mStartPropertySetThread->join() != NO_ERROR) {
749 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800750 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700751}
752
Mathias Agopian875d8e12013-06-07 15:35:48 -0700753size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800754 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700755}
756
Mathias Agopian875d8e12013-06-07 15:35:48 -0700757size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800758 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700759}
760
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800761// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800762
Jamie Gennis582270d2011-08-17 18:19:00 -0700763bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800764 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800765 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800766 return authenticateSurfaceTextureLocked(bufferProducer);
767}
768
769bool SurfaceFlinger::authenticateSurfaceTextureLocked(
770 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800771 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800772 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800773}
774
Brian Anderson6b376712017-04-04 10:51:39 -0700775status_t SurfaceFlinger::getSupportedFrameTimestamps(
776 std::vector<FrameEvent>* outSupported) const {
777 *outSupported = {
778 FrameEvent::REQUESTED_PRESENT,
779 FrameEvent::ACQUIRE,
780 FrameEvent::LATCH,
781 FrameEvent::FIRST_REFRESH_START,
782 FrameEvent::LAST_REFRESH_START,
783 FrameEvent::GPU_COMPOSITION_DONE,
784 FrameEvent::DEQUEUE_READY,
785 FrameEvent::RELEASE,
786 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700787 ConditionalLock _l(mStateLock,
788 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700789 if (!getHwComposer().hasCapability(
790 HWC2::Capability::PresentFenceIsNotReliable)) {
791 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
792 }
793 return NO_ERROR;
794}
795
Dan Stoza7f7da322014-05-02 15:26:25 -0700796status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
797 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800798 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700799 return BAD_VALUE;
800 }
801
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500802 if (!display.get())
803 return NAME_NOT_FOUND;
804
Jesse Hall692c7232012-11-08 15:41:56 -0800805 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700806 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800807 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700808 type = i;
809 break;
810 }
811 }
812
813 if (type < 0) {
814 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700815 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700816
Mathias Agopian8b736f12012-08-13 17:54:26 -0700817 // TODO: Not sure if display density should handled by SF any longer
818 class Density {
819 static int getDensityFromProperty(char const* propName) {
820 char property[PROPERTY_VALUE_MAX];
821 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800822 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700823 density = atoi(property);
824 }
825 return density;
826 }
827 public:
828 static int getEmuDensity() {
829 return getDensityFromProperty("qemu.sf.lcd_density"); }
830 static int getBuildDensity() {
831 return getDensityFromProperty("ro.sf.lcd_density"); }
832 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700833
Dan Stoza7f7da322014-05-02 15:26:25 -0700834 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700835
Steven Thomas6d8110b2017-08-31 18:24:21 -0700836 ConditionalLock _l(mStateLock,
837 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800838 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700839 DisplayInfo info = DisplayInfo();
840
Dan Stoza9e56aa02015-11-02 13:00:03 -0800841 float xdpi = hwConfig->getDpiX();
842 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700843
844 if (type == DisplayDevice::DISPLAY_PRIMARY) {
845 // The density of the device is provided by a build property
846 float density = Density::getBuildDensity() / 160.0f;
847 if (density == 0) {
848 // the build doesn't provide a density -- this is wrong!
849 // use xdpi instead
850 ALOGE("ro.sf.lcd_density must be defined as a build property");
851 density = xdpi / 160.0f;
852 }
853 if (Density::getEmuDensity()) {
854 // if "qemu.sf.lcd_density" is specified, it overrides everything
855 xdpi = ydpi = density = Density::getEmuDensity();
856 density /= 160.0f;
857 }
858 info.density = density;
859
860 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700861 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800862 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700863 } else {
864 // TODO: where should this value come from?
865 static const int TV_DENSITY = 213;
866 info.density = TV_DENSITY / 160.0f;
867 info.orientation = 0;
868 }
869
Dan Stoza9e56aa02015-11-02 13:00:03 -0800870 info.w = hwConfig->getWidth();
871 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700872 info.xdpi = xdpi;
873 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800874 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900875 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800876
Andy McFadden91b2ca82014-06-13 14:04:23 -0700877 // This is how far in advance a buffer must be queued for
878 // presentation at a given time. If you want a buffer to appear
879 // on the screen at time N, you must submit the buffer before
880 // (N - presentationDeadline).
881 //
882 // Normally it's one full refresh period (to give SF a chance to
883 // latch the buffer), but this can be reduced by configuring a
884 // DispSync offset. Any additional delays introduced by the hardware
885 // composer or panel must be accounted for here.
886 //
887 // We add an additional 1ms to allow for processing time and
888 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800889 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800890 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700891
892 // All non-virtual displays are currently considered secure.
893 info.secure = true;
894
Michael Wright28f24d02016-07-12 13:30:53 -0700895 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700896 }
897
Dan Stoza7f7da322014-05-02 15:26:25 -0700898 return NO_ERROR;
899}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700900
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800901status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700902 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800903 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700904 return BAD_VALUE;
905 }
906
907 // FIXME for now we always return stats for the primary display
908 memset(stats, 0, sizeof(*stats));
909 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
910 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
911 return NO_ERROR;
912}
913
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700914int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800915 if (display == nullptr) {
916 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800917 return BAD_VALUE;
918 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700919
920 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800921 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700922 return device->getActiveConfig();
923 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700924
Dan Stoza24a42e92015-03-09 10:04:11 -0700925 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700926}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700927
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700928void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
929 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
930 this);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700931 int currentMode = hw->getActiveConfig();
932
933 if (mode == currentMode) {
934 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
935 return;
936 }
937
Dominik Laskowski281644e2018-04-19 15:47:35 -0700938 if (hw->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700939 ALOGW("Trying to set config for virtual display");
940 return;
941 }
942
943 hw->setActiveConfig(mode);
Dominik Laskowski281644e2018-04-19 15:47:35 -0700944 getHwComposer().setActiveConfig(hw->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700945}
946
947status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
948 class MessageSetActiveConfig: public MessageBase {
949 SurfaceFlinger& mFlinger;
950 sp<IBinder> mDisplay;
951 int mMode;
952 public:
953 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
954 int mode) :
955 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
956 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700957 Vector<DisplayInfo> configs;
958 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700959 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700960 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700961 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700962 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700963 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700964 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800965 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700966 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700967 mMode, mDisplay.get());
Dominik Laskowski281644e2018-04-19 15:47:35 -0700968 } else if (hw->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700969 ALOGW("Attempt to set active config = %d for virtual display",
970 mMode);
971 } else {
972 mFlinger.setActiveConfigInternal(hw, mMode);
973 }
974 return true;
975 }
976 };
977 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
978 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700979 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700980}
Michael Wright28f24d02016-07-12 13:30:53 -0700981status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -0700982 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700983 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
984 return BAD_VALUE;
985 }
986
987 if (!display.get()) {
988 return NAME_NOT_FOUND;
989 }
990
991 int32_t type = NAME_NOT_FOUND;
992 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
993 if (display == mBuiltinDisplays[i]) {
994 type = i;
995 break;
996 }
997 }
998
999 if (type < 0) {
1000 return type;
1001 }
1002
Peiyong Lina52f0292018-03-14 17:26:31 -07001003 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001004 {
1005 ConditionalLock _l(mStateLock,
1006 std::this_thread::get_id() != mMainThreadId);
1007 modes = getHwComposer().getColorModes(type);
1008 }
Michael Wright28f24d02016-07-12 13:30:53 -07001009 outColorModes->clear();
1010 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1011
1012 return NO_ERROR;
1013}
1014
Peiyong Lina52f0292018-03-14 17:26:31 -07001015ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001016 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -07001017 if (device != nullptr) {
1018 return device->getActiveColorMode();
1019 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001020 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001021}
1022
1023void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001024 ColorMode mode, Dataspace dataSpace,
1025 RenderIntent renderIntent) {
Peiyong Lina52f0292018-03-14 17:26:31 -07001026 ColorMode currentMode = hw->getActiveColorMode();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001027 Dataspace currentDataSpace = hw->getCompositionDataSpace();
Peiyong Lin38e9a562018-04-10 16:24:20 -07001028 RenderIntent currentRenderIntent = hw->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001029
Peiyong Lin38e9a562018-04-10 16:24:20 -07001030 if (mode == currentMode && dataSpace == currentDataSpace &&
1031 renderIntent == currentRenderIntent) {
1032 return;
1033 }
1034
Dominik Laskowski281644e2018-04-19 15:47:35 -07001035 if (hw->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001036 ALOGW("Trying to set config for virtual display");
1037 return;
1038 }
1039
1040 hw->setActiveColorMode(mode);
1041 hw->setCompositionDataSpace(dataSpace);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001042 hw->setActiveRenderIntent(renderIntent);
Dominik Laskowski281644e2018-04-19 15:47:35 -07001043 getHwComposer().setActiveColorMode(hw->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001044
1045 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
1046 decodeColorMode(mode).c_str(), mode,
1047 decodeRenderIntent(renderIntent).c_str(), renderIntent,
1048 hw->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001049}
1050
1051
1052status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001053 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -07001054 class MessageSetActiveColorMode: public MessageBase {
1055 SurfaceFlinger& mFlinger;
1056 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -07001057 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001058 public:
1059 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -07001060 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -07001061 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1062 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -07001063 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001064 mFlinger.getDisplayColorModes(mDisplay, &modes);
1065 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -07001066 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001067 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1068 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001069 return true;
1070 }
1071 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1072 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001073 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1074 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Dominik Laskowski281644e2018-04-19 15:47:35 -07001075 } else if (hw->isVirtual()) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001076 ALOGW("Attempt to set active color mode %s %d for virtual display",
1077 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001078 } else {
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001079 mFlinger.setActiveColorModeInternal(hw, mMode, Dataspace::UNKNOWN,
1080 RenderIntent::COLORIMETRIC);
Michael Wright28f24d02016-07-12 13:30:53 -07001081 }
1082 return true;
1083 }
1084 };
1085 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1086 postMessageSync(msg);
1087 return NO_ERROR;
1088}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001089
Svetoslavd85084b2014-03-20 10:28:31 -07001090status_t SurfaceFlinger::clearAnimationFrameStats() {
1091 Mutex::Autolock _l(mStateLock);
1092 mAnimFrameTracker.clearStats();
1093 return NO_ERROR;
1094}
1095
1096status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1097 Mutex::Autolock _l(mStateLock);
1098 mAnimFrameTracker.getStats(outStats);
1099 return NO_ERROR;
1100}
1101
Dan Stozac4f471e2016-03-24 09:31:08 -07001102status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1103 HdrCapabilities* outCapabilities) const {
1104 Mutex::Autolock _l(mStateLock);
1105
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001106 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001107 if (displayDevice == nullptr) {
1108 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1109 return BAD_VALUE;
1110 }
1111
Peiyong Linfb069302018-04-25 14:34:31 -07001112 // At this point the DisplayDeivce should already be set up,
1113 // meaning the luminance information is already queried from
1114 // hardware composer and stored properly.
1115 const HdrCapabilities& capabilities = displayDevice->getHdrCapabilities();
1116 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1117 capabilities.getDesiredMaxLuminance(),
1118 capabilities.getDesiredMaxAverageLuminance(),
1119 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001120
1121 return NO_ERROR;
1122}
1123
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001124status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001125 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1126 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001127
Chia-I Wu90f669f2017-10-05 14:24:41 -07001128 if (mInjectVSyncs == enable) {
1129 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001130 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001131
1132 if (enable) {
1133 ALOGV("VSync Injections enabled");
1134 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001135 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique0fcde1b2017-12-20 16:50:21 -08001136 mInjectorEventThread =
1137 std::make_unique<impl::EventThread>(mVSyncInjector.get(), *this, false,
1138 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001139 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001140 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001141 } else {
1142 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001143 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001144 }
1145
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001146 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001147 });
1148 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001149 return NO_ERROR;
1150}
1151
1152status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001153 Mutex::Autolock _l(mStateLock);
1154
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001155 if (!mInjectVSyncs) {
1156 ALOGE("VSync Injections not enabled");
1157 return BAD_VALUE;
1158 }
1159 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1160 ALOGV("Injecting VSync inside SurfaceFlinger");
1161 mVSyncInjector->onInjectSyncEvent(when);
1162 }
1163 return NO_ERROR;
1164}
1165
Lloyd Pique755e3192018-01-31 16:46:15 -08001166status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1167 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001168 IPCThreadState* ipc = IPCThreadState::self();
1169 const int pid = ipc->getCallingPid();
1170 const int uid = ipc->getCallingUid();
1171 if ((uid != AID_SHELL) &&
1172 !PermissionCache::checkPermission(sDump, pid, uid)) {
1173 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1174 return PERMISSION_DENIED;
1175 }
1176
1177 // Try to acquire a lock for 1s, fail gracefully
1178 const status_t err = mStateLock.timedLock(s2ns(1));
1179 const bool locked = (err == NO_ERROR);
1180 if (!locked) {
1181 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1182 return TIMED_OUT;
1183 }
1184
1185 outLayers->clear();
1186 mCurrentState.traverseInZOrder([&](Layer* layer) {
1187 outLayers->push_back(layer->getLayerDebugInfo());
1188 });
1189
1190 mStateLock.unlock();
1191 return NO_ERROR;
1192}
1193
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001194// ----------------------------------------------------------------------------
1195
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001196sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1197 ISurfaceComposer::VsyncSource vsyncSource) {
1198 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1199 return mSFEventThread->createEventConnection();
1200 } else {
1201 return mEventThread->createEventConnection();
1202 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001203}
1204
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001205// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001206
1207void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001208 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001209}
1210
1211void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001212 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001213}
1214
1215void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001216 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001217}
1218
1219void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001220 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001221 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001222}
1223
1224status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001225 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001226 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001227}
1228
1229status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001230 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001231 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001232 if (res == NO_ERROR) {
1233 msg->wait();
1234 }
1235 return res;
1236}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001237
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001238void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001239 do {
1240 waitForEvent();
1241 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001242}
1243
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001244void SurfaceFlinger::enableHardwareVsync() {
1245 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001246 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001247 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001248 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1249 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001250 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001251 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001252}
1253
Jesse Hall948fe0c2013-10-14 12:56:09 -07001254void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001255 Mutex::Autolock _l(mHWVsyncLock);
1256
Jesse Hall948fe0c2013-10-14 12:56:09 -07001257 if (makeAvailable) {
1258 mHWVsyncAvailable = true;
1259 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001260 // Hardware vsync is not currently available, so abort the resync
1261 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001262 return;
1263 }
1264
David Sodman105b7dc2017-11-04 20:28:14 -07001265 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001266 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001267
1268 mPrimaryDispSync.reset();
1269 mPrimaryDispSync.setPeriod(period);
1270
1271 if (!mPrimaryHWVsyncEnabled) {
1272 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001273 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1274 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001275 mPrimaryHWVsyncEnabled = true;
1276 }
1277}
1278
Jesse Hall948fe0c2013-10-14 12:56:09 -07001279void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001280 Mutex::Autolock _l(mHWVsyncLock);
1281 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001282 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1283 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001284 mPrimaryDispSync.endResync();
1285 mPrimaryHWVsyncEnabled = false;
1286 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001287 if (makeUnavailable) {
1288 mHWVsyncAvailable = false;
1289 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001290}
1291
Tim Murray4a4e4a22016-04-19 16:29:23 +00001292void SurfaceFlinger::resyncWithRateLimit() {
1293 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001294
1295 // No explicit locking is needed here since EventThread holds a lock while calling this method
1296 static nsecs_t sLastResyncAttempted = 0;
1297 const nsecs_t now = systemTime();
1298 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001299 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001300 }
Dan Stoza57164302017-05-08 14:03:54 -07001301 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001302}
1303
Steven Thomasb02664d2017-07-26 18:48:28 -07001304void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1305 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001306 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001307 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001308 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001309 return;
1310 }
1311
1312 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001313 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001314 return;
1315 }
1316
Jamie Gennisd1700752013-10-14 12:22:52 -07001317 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001318
Jamie Gennisd1700752013-10-14 12:22:52 -07001319 { // Scope for the lock
1320 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001321 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001322 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001323 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001324 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001325
1326 if (needsHwVsync) {
1327 enableHardwareVsync();
1328 } else {
1329 disableHardwareVsync(false);
1330 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001331}
1332
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001333void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001334 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1335 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001336}
1337
Lloyd Pique715a2c12017-12-14 17:18:08 -08001338void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1339 HWC2::Connection connection) {
1340 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1341 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001342
Lloyd Piqueba04e622017-12-14 17:11:26 -08001343 // Ignore events that do not have the right sequenceId.
1344 if (sequenceId != getBE().mComposerSequenceId) {
1345 return;
1346 }
1347
Steven Thomasb02664d2017-07-26 18:48:28 -07001348 // Only lock if we're not on the main thread. This function is normally
1349 // called on a hwbinder thread, but for the primary display it's called on
1350 // the main thread with the state lock already held, so don't attempt to
1351 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001352 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001353
Lloyd Pique715a2c12017-12-14 17:18:08 -08001354 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001355
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001356 if (std::this_thread::get_id() == mMainThreadId) {
1357 // Process all pending hot plug events immediately if we are on the main thread.
1358 processDisplayHotplugEventsLocked();
1359 }
1360
Lloyd Piqueba04e622017-12-14 17:11:26 -08001361 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001362}
1363
Steven Thomasb02664d2017-07-26 18:48:28 -07001364void SurfaceFlinger::onRefreshReceived(int sequenceId,
1365 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001366 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001367 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001368 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001369 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001370 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001371}
1372
Dan Stoza9e56aa02015-11-02 13:00:03 -08001373void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001374 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001375 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001376 getHwComposer().setVsyncEnabled(disp,
1377 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001378}
1379
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001380// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001381void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001382 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001383 // Clear the drawing state so that the logic inside of
1384 // handleTransactionLocked will fire. It will determine the delta between
1385 // mCurrentState and mDrawingState and re-apply all changes when we make the
1386 // transition.
1387 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001388 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001389 mDisplays.clear();
1390}
1391
Steven Thomas050b2c82017-03-06 11:45:16 -08001392void SurfaceFlinger::updateVrFlinger() {
1393 if (!mVrFlinger)
1394 return;
1395 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001396 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001397 return;
1398 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001399
David Sodman105b7dc2017-11-04 20:28:14 -07001400 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001401 ALOGE("Vr flinger is only supported for remote hardware composer"
1402 " service connections. Ignoring request to transition to vr"
1403 " flinger.");
1404 mVrFlingerRequestsDisplay = false;
1405 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001406 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001407
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001408 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001409
Steven Thomasb02664d2017-07-26 18:48:28 -07001410 int currentDisplayPowerMode = getDisplayDeviceLocked(
1411 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001412
Steven Thomasb02664d2017-07-26 18:48:28 -07001413 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001414 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001415 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001416
Steven Thomasb02664d2017-07-26 18:48:28 -07001417 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001418 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001419 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1420 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001421 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001422
David Sodman105b7dc2017-11-04 20:28:14 -07001423 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1424 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001425
1426 if (vrFlingerRequestsDisplay) {
1427 mVrFlinger->GrantDisplayOwnership();
1428 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001429 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001430 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001431
1432 mVisibleRegionsDirty = true;
1433 invalidateHwcGeometry();
1434
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001435 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001436 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1437 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1438 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001439
Steven Thomasb02664d2017-07-26 18:48:28 -07001440 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001441 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001442 const nsecs_t period = activeConfig->getVsyncPeriod();
1443 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001444
Steven Thomasb02664d2017-07-26 18:48:28 -07001445 // Use phase of 0 since phase is not known.
1446 // Use latency of 0, which will snap to the ideal latency.
1447 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001448
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001449 android_atomic_or(1, &mRepaintEverything);
1450 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001451}
1452
Mathias Agopian4fec8732012-06-29 14:12:52 -07001453void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001454 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001455 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001456 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001457 bool frameMissed = !mHadClientComposition &&
1458 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001459 (mPreviousPresentFence->getSignalTime() ==
1460 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001461 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001462 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001463 mTimeStats.incrementMissedFrames();
1464 if (mPropagateBackpressure) {
1465 signalLayerUpdate();
1466 break;
1467 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001468 }
Dan Stoza50182882016-07-08 12:02:20 -07001469
Steven Thomas050b2c82017-03-06 11:45:16 -08001470 // Now that we're going to make it to the handleMessageTransaction()
1471 // call below it's safe to call updateVrFlinger(), which will
1472 // potentially trigger a display handoff.
1473 updateVrFlinger();
1474
Dan Stoza6b9454d2014-11-07 16:00:59 -08001475 bool refreshNeeded = handleMessageTransaction();
1476 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001477 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001478 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001479 // Signal a refresh if a transaction modified the window state,
1480 // a new buffer was latched, or if HWC has requested a full
1481 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001482 signalRefresh();
1483 }
1484 break;
1485 }
1486 case MessageQueue::REFRESH: {
1487 handleMessageRefresh();
1488 break;
1489 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001490 }
1491}
1492
Dan Stoza6b9454d2014-11-07 16:00:59 -08001493bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001494 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001495 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001496 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001497 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001498 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001499 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001500}
1501
Dan Stoza6b9454d2014-11-07 16:00:59 -08001502bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001503 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001504 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001505}
1506
1507void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001508 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001509
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001510 mRefreshPending = false;
1511
Chia-I Wu30505fb2018-03-26 16:20:31 -07001512 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001513
Chia-I Wu30505fb2018-03-26 16:20:31 -07001514 preComposition(refreshStartTime);
1515 rebuildLayerStacks();
1516 setUpHWComposer();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001517 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001518 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001519 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001520 doComposition();
Chia-I Wu30505fb2018-03-26 16:20:31 -07001521 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001522
David Sodman105b7dc2017-11-04 20:28:14 -07001523 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001524
1525 mHadClientComposition = false;
1526 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1527 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1528 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001529 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001530 }
Dan Stoza84d619e2018-03-28 17:07:36 -07001531 mVsyncModulator.setLastFrameUsedRenderEngine(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001532
Dan Stoza9e56aa02015-11-02 13:00:03 -08001533 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001534}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001535
Mathias Agopiancd60f992012-08-16 16:28:27 -07001536void SurfaceFlinger::doDebugFlashRegions()
1537{
1538 // is debugging enabled
1539 if (CC_LIKELY(!mDebugRegion))
1540 return;
1541
1542 const bool repaintEverything = mRepaintEverything;
1543 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1544 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001545 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001546 // transform the dirty region into this screen's coordinate space
1547 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1548 if (!dirtyRegion.isEmpty()) {
1549 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001550 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001551
1552 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001553 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001554 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001555 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1556
Mathias Agopianda27af92012-09-13 18:17:13 -07001557 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001558 }
1559 }
1560 }
1561
1562 postFramebuffer();
1563
1564 if (mDebugRegion > 1) {
1565 usleep(mDebugRegion * 1000);
1566 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001567
Dan Stoza9e56aa02015-11-02 13:00:03 -08001568 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001569 auto& displayDevice = mDisplays[displayId];
1570 if (!displayDevice->isDisplayOn()) {
1571 continue;
1572 }
1573
David Sodman105b7dc2017-11-04 20:28:14 -07001574 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1575 ALOGE_IF(result != NO_ERROR,
1576 "prepareFrame for display %zd failed:"
1577 " %d (%s)",
1578 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001579 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001580}
1581
Adrian Roos1e1a1282017-11-01 19:05:31 +01001582void SurfaceFlinger::doTracing(const char* where) {
1583 ATRACE_CALL();
1584 ATRACE_NAME(where);
1585 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001586 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001587 }
1588}
1589
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001590void SurfaceFlinger::logLayerStats() {
1591 ATRACE_CALL();
1592 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1593 int32_t hwcId = -1;
1594 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1595 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1596 if (displayDevice->isPrimary()) {
1597 hwcId = displayDevice->getHwcDisplayId();
1598 break;
1599 }
1600 }
1601 if (hwcId < 0) {
1602 ALOGE("LayerStats: Hmmm, no primary display?");
1603 return;
1604 }
1605 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1606 }
1607}
1608
Chia-I Wu30505fb2018-03-26 16:20:31 -07001609void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001610{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001611 ATRACE_CALL();
1612 ALOGV("preComposition");
1613
Mathias Agopiancd60f992012-08-16 16:28:27 -07001614 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001615 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001616 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001617 needExtraInvalidate = true;
1618 }
Robert Carr2047fae2016-11-28 14:09:09 -08001619 });
1620
Mathias Agopiancd60f992012-08-16 16:28:27 -07001621 if (needExtraInvalidate) {
1622 signalLayerUpdate();
1623 }
1624}
1625
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001626void SurfaceFlinger::updateCompositorTiming(
1627 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1628 std::shared_ptr<FenceTime>& presentFenceTime) {
1629 // Update queue of past composite+present times and determine the
1630 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001631 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001632 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001633 while (!getBE().mCompositePresentTimes.empty()) {
1634 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001635 // Cached values should have been updated before calling this method,
1636 // which helps avoid duplicate syscalls.
1637 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1638 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1639 break;
1640 }
1641 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001642 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001643 }
1644
1645 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001646 while (getBE().mCompositePresentTimes.size() > 16) {
1647 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001648 }
1649
Brian Andersond0010582017-03-07 13:20:31 -08001650 setCompositorTimingSnapped(
1651 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1652}
1653
1654void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1655 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001656 // Integer division and modulo round toward 0 not -inf, so we need to
1657 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001658 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001659 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1660 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1661
Brian Andersond0010582017-03-07 13:20:31 -08001662 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1663 if (idealLatency <= 0) {
1664 idealLatency = vsyncInterval;
1665 }
1666
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001667 // Snap the latency to a value that removes scheduling jitter from the
1668 // composition and present times, which often have >1ms of jitter.
1669 // Reducing jitter is important if an app attempts to extrapolate
1670 // something (such as user input) to an accurate diasplay time.
1671 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1672 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001673 nsecs_t bias = vsyncInterval / 2;
1674 int64_t extraVsyncs =
1675 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1676 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1677 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001678
David Sodman99974d22017-11-28 12:04:33 -08001679 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1680 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1681 getBE().mCompositorTiming.interval = vsyncInterval;
1682 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001683}
1684
Chia-I Wu30505fb2018-03-26 16:20:31 -07001685void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001686{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001687 ATRACE_CALL();
1688 ALOGV("postComposition");
1689
Brian Anderson3546a3f2016-07-14 11:51:14 -07001690 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001691 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001692 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001693 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001694 }
1695
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001696 // |mStateLock| not needed as we are on the main thread
1697 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001698
David Sodman73beded2017-11-15 11:56:06 -08001699 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001700 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001701 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001702 glCompositionDoneFenceTime =
1703 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001704 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001705 } else {
1706 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1707 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001708
David Sodman73beded2017-11-15 11:56:06 -08001709 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001710 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001711 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001712 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001713
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001714 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1715 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1716
Chia-I Wu30505fb2018-03-26 16:20:31 -07001717 // We use the refreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001718 // when we started doing work for this frame, but that should be okay
1719 // since updateCompositorTiming has snapping logic.
1720 updateCompositorTiming(
Chia-I Wu30505fb2018-03-26 16:20:31 -07001721 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001722 CompositorTiming compositorTiming;
1723 {
David Sodman99974d22017-11-28 12:04:33 -08001724 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1725 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001726 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001727
Robert Carr2047fae2016-11-28 14:09:09 -08001728 mDrawingState.traverseInZOrder([&](Layer* layer) {
1729 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001730 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001731 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001732 recordBufferingStats(layer->getName().string(),
1733 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001734 }
Robert Carr2047fae2016-11-28 14:09:09 -08001735 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001736
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001737 if (presentFenceTime->isValid()) {
1738 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001739 enableHardwareVsync();
1740 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001741 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001742 }
1743 }
1744
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001745 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001746 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001747 enableHardwareVsync();
1748 }
1749 }
1750
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001751 if (mAnimCompositionPending) {
1752 mAnimCompositionPending = false;
1753
Brian Anderson4e606e32017-03-16 15:34:57 -07001754 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001755 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001756 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001757 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001758 // The HWC doesn't support present fences, so use the refresh
1759 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001760 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001761 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001762 mAnimFrameTracker.setActualPresentTime(presentTime);
1763 }
1764 mAnimFrameTracker.advanceFrame();
1765 }
Dan Stozab90cf072015-03-05 11:05:59 -08001766
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001767 mTimeStats.incrementTotalFrames();
1768 if (mHadClientComposition) {
1769 mTimeStats.incrementClientCompositionFrames();
1770 }
1771
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001772 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1773 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001774 return;
1775 }
1776
1777 nsecs_t currentTime = systemTime();
1778 if (mHasPoweredOff) {
1779 mHasPoweredOff = false;
1780 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001781 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001782 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001783 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1784 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001785 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001786 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001787 }
David Sodman4a36e932017-11-07 14:29:47 -08001788 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001789 }
David Sodman4a36e932017-11-07 14:29:47 -08001790 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001791}
1792
1793void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001794 ATRACE_CALL();
1795 ALOGV("rebuildLayerStacks");
1796
Mathias Agopiancd60f992012-08-16 16:28:27 -07001797 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001798 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001799 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001800 mVisibleRegionsDirty = false;
1801 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001802
Jeff Sharkey76488112017-02-27 14:15:18 -07001803 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1804 Region opaqueRegion;
1805 Region dirtyRegion;
1806 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001807 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001808 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1809 const Transform& tr(displayDevice->getTransform());
1810 const Rect bounds(displayDevice->getBounds());
1811 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001812 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001813
Jeff Sharkey76488112017-02-27 14:15:18 -07001814 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001815 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001816 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1817 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001818 Region drawRegion(tr.transform(
1819 layer->visibleNonTransparentRegion));
1820 drawRegion.andSelf(bounds);
1821 if (!drawRegion.isEmpty()) {
1822 layersSortedByZ.add(layer);
1823 } else {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001824 // Clear out the HWC layer if this layer was
1825 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001826 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001827 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001828 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001829 } else {
1830 // WM changes displayDevice->layerStack upon sleep/awake.
1831 // Here we make sure we delete the HWC layers even if
1832 // WM changed their layer stack.
1833 hwcLayerDestroyed = layer->destroyHwcLayer(
1834 displayDevice->getHwcDisplayId());
Chia-I Wu83806892017-11-16 10:50:20 -08001835 }
1836
1837 // If a layer is not going to get a release fence because
1838 // it is invisible, but it is also going to release its
1839 // old buffer, add it to the list of layers needing
1840 // fences.
1841 if (hwcLayerDestroyed) {
1842 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1843 mLayersWithQueuedFrames.cend(), layer);
1844 if (found != mLayersWithQueuedFrames.cend()) {
1845 layersNeedingFences.add(layer);
1846 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001847 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001848 });
1849 }
1850 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001851 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001852 displayDevice->undefinedRegion.set(bounds);
1853 displayDevice->undefinedRegion.subtractSelf(
1854 tr.transform(opaqueRegion));
1855 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001856 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001857 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001858}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001859
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001860// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001861// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001862// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001863// - Dataspace::DISPLAY_P3
1864// - Dataspace::V0_SCRGB_LINEAR
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001865// The returned HDR data space is one of
1866// - Dataspace::UNKNOWN
1867// - Dataspace::BT2020_HLG
1868// - Dataspace::BT2020_PQ
1869Dataspace SurfaceFlinger::getBestDataspace(
1870 const sp<const DisplayDevice>& displayDevice, Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001871 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001872 *outHdrDataSpace = Dataspace::UNKNOWN;
1873
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001874 for (const auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1875 switch (layer->getDataSpace()) {
1876 case Dataspace::V0_SCRGB:
1877 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001878 bestDataSpace = Dataspace::V0_SCRGB_LINEAR;
Peiyong Linf59a7192018-04-25 11:19:31 -07001879 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001880 case Dataspace::DISPLAY_P3:
Chia-I Wu7112a112018-05-07 15:27:06 -07001881 if (bestDataSpace == Dataspace::SRGB) {
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001882 bestDataSpace = Dataspace::DISPLAY_P3;
1883 }
1884 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001885 case Dataspace::BT2020_PQ:
1886 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001887 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001888 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001889 case Dataspace::BT2020_HLG:
1890 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001891 // When there's mixed PQ content and HLG content, we set the HDR
1892 // data space to be BT2020_PQ and convert HLG to PQ.
1893 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1894 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001895 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001896 break;
1897 default:
1898 break;
1899 }
Romain Guy54f154a2017-10-24 21:40:32 +01001900 }
1901
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001902 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001903}
1904
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001905// Pick the ColorMode / Dataspace for the display device.
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001906void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& displayDevice,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001907 ColorMode* outMode, Dataspace* outDataSpace,
1908 RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001909 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1910 *outMode = ColorMode::NATIVE;
1911 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001912 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001913 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001914 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001915
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001916 Dataspace hdrDataSpace;
1917 Dataspace bestDataSpace = getBestDataspace(displayDevice, &hdrDataSpace);
1918
1919 if (hdrDataSpace == Dataspace::BT2020_PQ) {
1920 // Hardware composer can handle BT2100 ColorMode only when
1921 // - colorimetrical tone mapping is supported, or
1922 // - Auto mode is turned on and enhanced tone mapping is supported.
1923 if (displayDevice->hasBT2100PQColorimetricSupport() ||
1924 (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
1925 displayDevice->hasBT2100PQEnhanceSupport())) {
1926 *outMode = ColorMode::BT2100_PQ;
1927 *outDataSpace = Dataspace::BT2020_PQ;
1928 } else if (displayDevice->hasHDR10Support()) {
1929 // Legacy HDR support. HDR layers are treated as UNKNOWN layers.
1930 hdrDataSpace = Dataspace::UNKNOWN;
1931 } else {
1932 // Simulate PQ through RenderEngine, pick DISPLAY_P3 color mode.
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001933 *outMode = ColorMode::DISPLAY_P3;
1934 *outDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001935 }
1936 } else if (hdrDataSpace == Dataspace::BT2020_HLG) {
1937 if (displayDevice->hasBT2100HLGColorimetricSupport() ||
1938 (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
1939 displayDevice->hasBT2100HLGEnhanceSupport())) {
1940 *outMode = ColorMode::BT2100_HLG;
1941 *outDataSpace = Dataspace::BT2020_HLG;
1942 } else if (displayDevice->hasHLGSupport()) {
1943 // Legacy HDR support. HDR layers are treated as UNKNOWN layers.
1944 hdrDataSpace = Dataspace::UNKNOWN;
1945 } else {
1946 // Simulate HLG through RenderEngine, pick DISPLAY_P3 color mode.
1947 *outMode = ColorMode::DISPLAY_P3;
1948 *outDataSpace = Dataspace::DISPLAY_P3;
1949 }
1950 }
1951
1952 // At this point, there's no HDR layer.
1953 if (hdrDataSpace == Dataspace::UNKNOWN) {
1954 switch (bestDataSpace) {
1955 case Dataspace::DISPLAY_P3:
1956 case Dataspace::V0_SCRGB_LINEAR:
1957 *outMode = ColorMode::DISPLAY_P3;
1958 *outDataSpace = Dataspace::DISPLAY_P3;
1959 break;
1960 default:
1961 *outMode = ColorMode::SRGB;
Chia-I Wu7112a112018-05-07 15:27:06 -07001962 *outDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001963 break;
1964 }
1965 }
1966 *outRenderIntent = pickRenderIntent(displayDevice, *outMode);
1967}
1968
1969RenderIntent SurfaceFlinger::pickRenderIntent(const sp<DisplayDevice>& displayDevice,
1970 ColorMode colorMode) const {
1971 // Native Mode means the display is not color managed, and whichever
1972 // render intent is picked doesn't matter, thus return
1973 // RenderIntent::COLORIMETRIC as default here.
1974 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1975 return RenderIntent::COLORIMETRIC;
1976 }
1977
1978 // In Auto Color Mode, we want to strech to panel color space, right now
1979 // only the built-in display supports it.
1980 if (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
1981 mBuiltinDisplaySupportsEnhance && displayDevice->isPrimary()) {
1982 switch (colorMode) {
1983 case ColorMode::DISPLAY_P3:
1984 case ColorMode::SRGB:
1985 return RenderIntent::ENHANCE;
1986 // In Auto Color Mode, BT2100_PQ and BT2100_HLG will only be picked
1987 // when TONE_MAP_ENHANCE or TONE_MAP_COLORIMETRIC is supported.
1988 // If TONE_MAP_ENHANCE is not supported, fall back to TONE_MAP_COLORIMETRIC.
1989 case ColorMode::BT2100_PQ:
1990 return displayDevice->hasBT2100PQEnhanceSupport() ?
1991 RenderIntent::TONE_MAP_ENHANCE : RenderIntent::TONE_MAP_COLORIMETRIC;
1992 case ColorMode::BT2100_HLG:
1993 return displayDevice->hasBT2100HLGEnhanceSupport() ?
1994 RenderIntent::TONE_MAP_ENHANCE : RenderIntent::TONE_MAP_COLORIMETRIC;
1995 // This statement shouldn't be reached, switch cases will always
1996 // cover all possible ColorMode returned by pickColorMode.
1997 default:
1998 return RenderIntent::COLORIMETRIC;
1999 }
2000 }
2001
2002 // Either enhance is not supported or we are in natural mode.
2003
2004 // Natural Mode means it's color managed and the color must be right,
2005 // thus we pick RenderIntent::COLORIMETRIC as render intent for non-HDR
2006 // content and pick RenderIntent::TONE_MAP_COLORIMETRIC for HDR content.
2007 switch (colorMode) {
2008 // In Natural Color Mode, BT2100_PQ and BT2100_HLG will only be picked
2009 // when TONE_MAP_COLORIMETRIC is supported.
2010 case ColorMode::BT2100_PQ:
2011 case ColorMode::BT2100_HLG:
2012 return RenderIntent::TONE_MAP_COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002013 default:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002014 return RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002015 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002016}
2017
Chia-I Wu30505fb2018-03-26 16:20:31 -07002018void SurfaceFlinger::setUpHWComposer() {
2019 ATRACE_CALL();
2020 ALOGV("setUpHWComposer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08002021
Jesse Hall028dc8f2013-08-20 16:35:32 -07002022 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Dan Stozac7a25ad2018-04-12 11:45:09 -07002023 bool dirty = !mDisplays[dpy]->getDirtyRegion(mRepaintEverything).isEmpty();
Jesse Hallb7a05492014-08-14 15:45:06 -07002024 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
2025 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
2026
2027 // If nothing has changed (!dirty), don't recompose.
2028 // If something changed, but we don't currently have any visible layers,
2029 // and didn't when we last did a composition, then skip it this time.
2030 // The second rule does two things:
2031 // - When all layers are removed from a display, we'll emit one black
2032 // frame, then nothing more until we get new layers.
2033 // - When a display is created with a private layer stack, we won't
2034 // emit any black frames until a layer is added to the layer stack.
2035 bool mustRecompose = dirty && !(empty && wasEmpty);
2036
Dominik Laskowski281644e2018-04-19 15:47:35 -07002037 ALOGV_IF(mDisplays[dpy]->isVirtual(),
Jesse Hallb7a05492014-08-14 15:45:06 -07002038 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
2039 mustRecompose ? "doing" : "skipping",
2040 dirty ? "+" : "-",
2041 empty ? "+" : "-",
2042 wasEmpty ? "+" : "-");
2043
Dan Stoza71433162014-02-04 16:22:36 -08002044 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07002045
2046 if (mustRecompose) {
2047 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
2048 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07002049 }
2050
Chia-I Wu30505fb2018-03-26 16:20:31 -07002051 // build the h/w work list
2052 if (CC_UNLIKELY(mGeometryInvalid)) {
2053 mGeometryInvalid = false;
2054 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2055 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
2056 const auto hwcId = displayDevice->getHwcDisplayId();
2057 if (hwcId >= 0) {
2058 const Vector<sp<Layer>>& currentLayers(
2059 displayDevice->getVisibleLayersSortedByZ());
2060 for (size_t i = 0; i < currentLayers.size(); i++) {
2061 const auto& layer = currentLayers[i];
2062 if (!layer->hasHwcLayer(hwcId)) {
2063 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
2064 layer->forceClientComposition(hwcId);
2065 continue;
2066 }
2067 }
2068
2069 layer->setGeometry(displayDevice, i);
2070 if (mDebugDisableHWC || mDebugRegion) {
2071 layer->forceClientComposition(hwcId);
2072 }
2073 }
2074 }
2075 }
2076 }
2077
Chia-I Wu30505fb2018-03-26 16:20:31 -07002078 // Set the per-frame data
2079 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2080 auto& displayDevice = mDisplays[displayId];
2081 const auto hwcId = displayDevice->getHwcDisplayId();
2082
2083 if (hwcId < 0) {
2084 continue;
2085 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07002086 if (mDrawingState.colorMatrixChanged) {
2087 displayDevice->setColorTransform(mDrawingState.colorMatrix);
2088 status_t result = getBE().mHwc->setColorTransform(hwcId, mDrawingState.colorMatrix);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002089 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
2090 "display %zd: %d", displayId, result);
2091 }
2092 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002093 if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2094 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Peiyong Lin62665892018-04-16 11:07:44 -07002095 !displayDevice->hasHDR10Support()) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07002096 layer->forceClientComposition(hwcId);
2097 }
Peiyong Linf59a7192018-04-25 11:19:31 -07002098 if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
2099 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
2100 !displayDevice->hasHLGSupport()) {
2101 layer->forceClientComposition(hwcId);
2102 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002103
2104 if (layer->getForceClientComposition(hwcId)) {
2105 ALOGV("[%s] Requesting Client composition", layer->getName().string());
2106 layer->setCompositionType(hwcId, HWC2::Composition::Client);
2107 continue;
2108 }
2109
2110 layer->setPerFrameData(displayDevice);
2111 }
2112
2113 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002114 ColorMode colorMode;
2115 Dataspace dataSpace;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002116 RenderIntent renderIntent;
2117 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
2118 setActiveColorModeInternal(displayDevice, colorMode, dataSpace, renderIntent);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002119 }
2120 }
2121
Chia-I Wu28f320b2018-05-03 11:02:56 -07002122 mDrawingState.colorMatrixChanged = false;
Chia-I Wu30505fb2018-03-26 16:20:31 -07002123
Dan Stoza9e56aa02015-11-02 13:00:03 -08002124 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002125 auto& displayDevice = mDisplays[displayId];
2126 if (!displayDevice->isDisplayOn()) {
2127 continue;
2128 }
2129
David Sodman105b7dc2017-11-04 20:28:14 -07002130 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002131 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2132 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002133 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002134}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002135
Mathias Agopiancd60f992012-08-16 16:28:27 -07002136void SurfaceFlinger::doComposition() {
2137 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002138 ALOGV("doComposition");
2139
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002140 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002141 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002142 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002143 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002144 // transform the dirty region into this screen's coordinate space
2145 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002146
2147 // repaint the framebuffer (if needed)
2148 doDisplayComposition(hw, dirtyRegion);
2149
Mathias Agopiancd60f992012-08-16 16:28:27 -07002150 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002151 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002152 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002153 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002154 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002155}
2156
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002157void SurfaceFlinger::postFramebuffer()
2158{
Mathias Agopian841cde52012-03-01 15:44:37 -08002159 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002160 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002161
Mathias Agopiana44b0412011-10-16 18:46:35 -07002162 const nsecs_t now = systemTime();
2163 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002164
Dan Stoza9e56aa02015-11-02 13:00:03 -08002165 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2166 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002167 if (!displayDevice->isDisplayOn()) {
2168 continue;
2169 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002170 const auto hwcId = displayDevice->getHwcDisplayId();
2171 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002172 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002173 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002174 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002175 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002176 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002177 // The layer buffer from the previous frame (if any) is released
2178 // by HWC only when the release fence from this frame (if any) is
2179 // signaled. Always get the release fence from HWC first.
2180 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002181 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002182
2183 // If the layer was client composited in the previous frame, we
2184 // need to merge with the previous client target acquire fence.
2185 // Since we do not track that, always merge with the current
2186 // client target acquire fence when it is available, even though
2187 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002188 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002189 releaseFence = Fence::merge("LayerRelease", releaseFence,
2190 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002191 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002192
David Sodmanb8af7922017-12-21 15:17:55 -08002193 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002194 }
Chia-I Wu83806892017-11-16 10:50:20 -08002195
2196 // We've got a list of layers needing fences, that are disjoint with
2197 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2198 // supply them with the present fence.
2199 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002200 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002201 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002202 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002203 }
2204 }
2205
Dan Stoza9e56aa02015-11-02 13:00:03 -08002206 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002207 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002208 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002209 }
2210
Mathias Agopiana44b0412011-10-16 18:46:35 -07002211 mLastSwapBufferTime = systemTime() - now;
2212 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002213
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002214 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002215 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2216 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2217 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2218 logFrameStats();
2219 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002220 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002221}
2222
Mathias Agopian87baae12012-07-31 12:38:26 -07002223void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002224{
Mathias Agopian841cde52012-03-01 15:44:37 -08002225 ATRACE_CALL();
2226
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002227 // here we keep a copy of the drawing state (that is the state that's
2228 // going to be overwritten by handleTransactionLocked()) outside of
2229 // mStateLock so that the side-effects of the State assignment
2230 // don't happen with mStateLock held (which can cause deadlocks).
2231 State drawingState(mDrawingState);
2232
Mathias Agopianca4d3602011-05-19 15:38:14 -07002233 Mutex::Autolock _l(mStateLock);
2234 const nsecs_t now = systemTime();
2235 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002236
Mathias Agopianca4d3602011-05-19 15:38:14 -07002237 // Here we're guaranteed that some transaction flags are set
2238 // so we can call handleTransactionLocked() unconditionally.
2239 // We call getTransactionFlags(), which will also clear the flags,
2240 // with mStateLock held to guarantee that mCurrentState won't change
2241 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002242
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002243 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002244 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002245 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002246
Mathias Agopianca4d3602011-05-19 15:38:14 -07002247 mLastTransactionTime = systemTime() - now;
2248 mDebugInTransaction = 0;
2249 invalidateHwcGeometry();
2250 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002251}
2252
Lloyd Pique715a2c12017-12-14 17:18:08 -08002253DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002254 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002255 // Figure out whether the event is for the primary display or an
2256 // external display by matching the Hwc display id against one for a
2257 // connected display. If we did not find a match, we then check what
2258 // displays are not already connected to determine the type. If we don't
2259 // have a connected primary display, we assume the new display is meant to
2260 // be the primary display, and then if we don't have an external display,
2261 // we assume it is that.
2262 const auto primaryDisplayId =
2263 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2264 const auto externalDisplayId =
2265 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2266 if (primaryDisplayId && primaryDisplayId == display) {
2267 return DisplayDevice::DISPLAY_PRIMARY;
2268 } else if (externalDisplayId && externalDisplayId == display) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002269 return DisplayDevice::DISPLAY_EXTERNAL;
Lloyd Pique715a2c12017-12-14 17:18:08 -08002270 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2271 return DisplayDevice::DISPLAY_PRIMARY;
2272 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2273 return DisplayDevice::DISPLAY_EXTERNAL;
2274 }
2275
2276 return DisplayDevice::DISPLAY_ID_INVALID;
2277}
2278
Lloyd Piqueba04e622017-12-14 17:11:26 -08002279void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2280 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002281 auto displayType = determineDisplayType(event.display, event.connection);
2282 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2283 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2284 continue;
2285 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002286
2287 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2288 ALOGE("External displays are not supported by the vr hardware composer.");
2289 continue;
2290 }
2291
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002292 const auto displayId =
2293 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
2294 if (displayId) {
2295 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.display, *displayId);
2296 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002297
2298 if (event.connection == HWC2::Connection::Connected) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002299 if (!mBuiltinDisplays[displayType].get()) {
2300 ALOGV("Creating built in display %d", displayType);
2301 mBuiltinDisplays[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002302 DisplayDeviceState info;
2303 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002304 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2305 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002306 info.isSecure = true; // All physical displays are currently considered secure.
Steven Thomaseb6d2052018-03-20 15:40:48 -07002307 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
2308 mInterceptor->saveDisplayCreation(info);
2309 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002310 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002311 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002312
Lloyd Piquefcd86612017-12-14 17:15:36 -08002313 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2314 if (idx >= 0) {
2315 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002316 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002317 mCurrentState.displays.removeItemsAt(idx);
2318 }
2319 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002320 }
2321
2322 processDisplayChangesLocked();
2323 }
2324
2325 mPendingHotplugEvents.clear();
2326}
2327
Lloyd Pique99d3da52018-01-22 17:48:03 -08002328sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2329 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2330 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002331 bool hasWideColorGamut = false;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002332 std::unordered_map<ColorMode, std::vector<RenderIntent>> hdrAndRenderIntents;
2333
Lloyd Pique99d3da52018-01-22 17:48:03 -08002334 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002335 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002336 for (ColorMode colorMode : modes) {
2337 switch (colorMode) {
2338 case ColorMode::DISPLAY_P3:
2339 case ColorMode::ADOBE_RGB:
2340 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002341 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002342 break;
2343 default:
2344 break;
2345 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002346
2347 std::vector<RenderIntent> renderIntents = getHwComposer().getRenderIntents(hwcId,
2348 colorMode);
2349 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2350 for (auto intent : renderIntents) {
2351 if (intent == RenderIntent::ENHANCE) {
2352 mBuiltinDisplaySupportsEnhance = true;
2353 break;
2354 }
2355 }
2356 }
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002357
2358 if (colorMode == ColorMode::BT2100_PQ || colorMode == ColorMode::BT2100_HLG) {
2359 hdrAndRenderIntents.emplace(colorMode, renderIntents);
2360 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002361 }
2362 }
2363
Peiyong Lin62665892018-04-16 11:07:44 -07002364 HdrCapabilities hdrCapabilities;
2365 getHwComposer().getHdrCapabilities(hwcId, &hdrCapabilities);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002366
2367 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2368 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2369
2370 /*
2371 * Create our display's surface
2372 */
2373 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2374 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002375 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002376 renderSurface->setNativeWindow(nativeWindow.get());
2377 const int displayWidth = renderSurface->queryWidth();
2378 const int displayHeight = renderSurface->queryHeight();
2379
2380 // Make sure that composition can never be stalled by a virtual display
2381 // consumer that isn't processing buffers fast enough. We have to do this
2382 // in two places:
2383 // * Here, in case the display is composed entirely by HWC.
2384 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2385 // window's swap interval in eglMakeCurrent, so they'll override the
2386 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002387 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002388 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2389 }
2390
2391 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002392 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002393
2394 sp<DisplayDevice> hw =
2395 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2396 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
Peiyong Lin0ac5f4e2018-04-19 22:06:34 -07002397 hasWideColorGamut, hdrCapabilities,
2398 getHwComposer().getSupportedPerFrameMetadata(hwcId),
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002399 hdrAndRenderIntents, initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002400
2401 if (maxFrameBufferAcquiredBuffers >= 3) {
2402 nativeWindowSurface->preallocateBuffers();
2403 }
2404
2405 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002406 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2407 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002408 defaultColorMode = ColorMode::SRGB;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002409 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002410 }
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002411 setActiveColorModeInternal(hw, defaultColorMode, defaultDataSpace,
2412 RenderIntent::COLORIMETRIC);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002413 hw->setLayerStack(state.layerStack);
2414 hw->setProjection(state.orientation, state.viewport, state.frame);
2415 hw->setDisplayName(state.displayName);
2416
2417 return hw;
2418}
2419
Lloyd Pique347200f2017-12-14 17:00:15 -08002420void SurfaceFlinger::processDisplayChangesLocked() {
2421 // here we take advantage of Vector's copy-on-write semantics to
2422 // improve performance by skipping the transaction entirely when
2423 // know that the lists are identical
2424 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2425 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2426 if (!curr.isIdenticalTo(draw)) {
2427 mVisibleRegionsDirty = true;
2428 const size_t cc = curr.size();
2429 size_t dc = draw.size();
2430
2431 // find the displays that were removed
2432 // (ie: in drawing state but not in current state)
2433 // also handle displays that changed
2434 // (ie: displays that are in both lists)
2435 for (size_t i = 0; i < dc;) {
2436 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2437 if (j < 0) {
2438 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002439 // Call makeCurrent() on the primary display so we can
2440 // be sure that nothing associated with this display
2441 // is current.
2442 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2443 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2444 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2445 if (hw != nullptr) hw->disconnect(getHwComposer());
2446 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2447 mEventThread->onHotplugReceived(draw[i].type, false);
2448 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002449 } else {
2450 // this display is in both lists. see if something changed.
2451 const DisplayDeviceState& state(curr[j]);
2452 const wp<IBinder>& display(curr.keyAt(j));
2453 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2454 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2455 if (state_binder != draw_binder) {
2456 // changing the surface is like destroying and
2457 // recreating the DisplayDevice, so we just remove it
2458 // from the drawing state, so that it get re-added
2459 // below.
2460 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2461 if (hw != nullptr) hw->disconnect(getHwComposer());
2462 mDisplays.removeItem(display);
2463 mDrawingState.displays.removeItemsAt(i);
2464 dc--;
2465 // at this point we must loop to the next item
2466 continue;
2467 }
2468
2469 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2470 if (disp != nullptr) {
2471 if (state.layerStack != draw[i].layerStack) {
2472 disp->setLayerStack(state.layerStack);
2473 }
2474 if ((state.orientation != draw[i].orientation) ||
2475 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2476 disp->setProjection(state.orientation, state.viewport, state.frame);
2477 }
2478 if (state.width != draw[i].width || state.height != draw[i].height) {
2479 disp->setDisplaySize(state.width, state.height);
2480 }
2481 }
2482 }
2483 ++i;
2484 }
2485
2486 // find displays that were added
2487 // (ie: in current state but not in drawing state)
2488 for (size_t i = 0; i < cc; i++) {
2489 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2490 const DisplayDeviceState& state(curr[i]);
2491
2492 sp<DisplaySurface> dispSurface;
2493 sp<IGraphicBufferProducer> producer;
2494 sp<IGraphicBufferProducer> bqProducer;
2495 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002496 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002497
2498 int32_t hwcId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002499 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002500 // Virtual displays without a surface are dormant:
2501 // they have external state (layer stack, projection,
2502 // etc.) but no internal state (i.e. a DisplayDevice).
2503 if (state.surface != nullptr) {
2504 // Allow VR composer to use virtual displays.
2505 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2506 int width = 0;
2507 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2508 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2509 int height = 0;
2510 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2511 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2512 int intFormat = 0;
2513 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2514 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002515 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002516
2517 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2518 }
2519
2520 // TODO: Plumb requested format back up to consumer
2521
2522 sp<VirtualDisplaySurface> vds =
2523 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2524 bqProducer, bqConsumer,
2525 state.displayName);
2526
2527 dispSurface = vds;
2528 producer = vds;
2529 }
2530 } else {
2531 ALOGE_IF(state.surface != nullptr,
2532 "adding a supported display, but rendering "
2533 "surface is provided (%p), ignoring it",
2534 state.surface.get());
2535
2536 hwcId = state.type;
2537 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2538 producer = bqProducer;
2539 }
2540
2541 const wp<IBinder>& display(curr.keyAt(i));
2542 if (dispSurface != nullptr) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002543 mDisplays.add(display,
2544 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2545 producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002546 if (!state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002547 mEventThread->onHotplugReceived(state.type, true);
2548 }
2549 }
2550 }
2551 }
2552 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002553
2554 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002555}
2556
Mathias Agopian87baae12012-07-31 12:38:26 -07002557void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002558{
Dan Stoza7dde5992015-05-22 09:51:44 -07002559 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002560 mCurrentState.traverseInZOrder([](Layer* layer) {
2561 layer->notifyAvailableFrames();
2562 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002563
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002564 /*
2565 * Traversal of the children
2566 * (perform the transaction for each of them if needed)
2567 */
2568
Mathias Agopian3559b072012-08-15 13:46:03 -07002569 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002570 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002571 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002572 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002573
2574 const uint32_t flags = layer->doTransaction(0);
2575 if (flags & Layer::eVisibleRegion)
2576 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002577 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002578 }
2579
2580 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002581 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002582 */
2583
Mathias Agopiane57f2922012-08-09 16:29:12 -07002584 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002585 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002586 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002587 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002588
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002589 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002590 // The transform hint might have changed for some layers
2591 // (either because a display has changed, or because a layer
2592 // as changed).
2593 //
2594 // Walk through all the layers in currentLayers,
2595 // and update their transform hint.
2596 //
2597 // If a layer is visible only on a single display, then that
2598 // display is used to calculate the hint, otherwise we use the
2599 // default display.
2600 //
2601 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2602 // the hint is set before we acquire a buffer from the surface texture.
2603 //
2604 // NOTE: layer transactions have taken place already, so we use their
2605 // drawing state. However, SurfaceFlinger's own transaction has not
2606 // happened yet, so we must use the current state layer list
2607 // (soon to become the drawing state list).
2608 //
2609 sp<const DisplayDevice> disp;
2610 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002611 bool first = true;
2612 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002613 // NOTE: we rely on the fact that layers are sorted by
2614 // layerStack first (so we don't have to traverse the list
2615 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002616 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002617 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002618 currentlayerStack = layerStack;
2619 // figure out if this layerstack is mirrored
2620 // (more than one display) if so, pick the default display,
2621 // if not, pick the only display it's on.
2622 disp.clear();
2623 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2624 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002625 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002626 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002627 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002628 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002629 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002630 break;
2631 }
2632 }
2633 }
2634 }
Chet Haase91d25932013-04-11 15:24:55 -07002635
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002636 if (disp == nullptr) {
2637 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2638 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002639
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002640 // could be null when this layer is using a layerStack
2641 // that is not visible on any display. Also can occur at
2642 // screen off/on times.
2643 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002644 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002645
2646 // disp can be null if there is no display available at all to get
2647 // the transform hint from.
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002648 if (disp != nullptr) {
2649 layer->updateTransformHint(disp);
2650 }
Robert Carr2047fae2016-11-28 14:09:09 -08002651
2652 first = false;
2653 });
Mathias Agopian84300952012-11-21 16:02:13 -08002654 }
2655
2656
Mathias Agopian3559b072012-08-15 13:46:03 -07002657 /*
2658 * Perform our own transaction if needed
2659 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002660
2661 if (mLayersAdded) {
2662 mLayersAdded = false;
2663 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002664 mVisibleRegionsDirty = true;
2665 }
2666
2667 // some layers might have been removed, so
2668 // we need to update the regions they're exposing.
2669 if (mLayersRemoved) {
2670 mLayersRemoved = false;
2671 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002672 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002673 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002674 // this layer is not visible anymore
2675 // TODO: we could traverse the tree from front to back and
2676 // compute the actual visible region
2677 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002678 Region visibleReg;
2679 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002680 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002681 }
Robert Carr2047fae2016-11-28 14:09:09 -08002682 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002683 }
2684
2685 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002686
2687 updateCursorAsync();
2688}
2689
2690void SurfaceFlinger::updateCursorAsync()
2691{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002692 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2693 auto& displayDevice = mDisplays[displayId];
2694 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002695 continue;
2696 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002697
2698 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2699 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002700 }
2701 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002702}
2703
2704void SurfaceFlinger::commitTransaction()
2705{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002706 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002707 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002708 for (const auto& l : mLayersPendingRemoval) {
2709 recordBufferingStats(l->getName().string(),
2710 l->getOccupancyHistory(true));
2711 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002712 }
2713 mLayersPendingRemoval.clear();
2714 }
2715
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002716 // If this transaction is part of a window animation then the next frame
2717 // we composite should be considered an animation as well.
2718 mAnimCompositionPending = mAnimTransactionPending;
2719
Mathias Agopian4fec8732012-06-29 14:12:52 -07002720 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002721 // clear the "changed" flags in current state
2722 mCurrentState.colorMatrixChanged = false;
2723
Robert Carr1f0a16a2016-10-24 16:27:39 -07002724 mDrawingState.traverseInZOrder([](Layer* layer) {
2725 layer->commitChildList();
2726 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002727 mTransactionPending = false;
2728 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002729 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002730}
2731
Chia-I Wuab0c3192017-08-01 11:29:00 -07002732void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002733 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002734{
Mathias Agopian841cde52012-03-01 15:44:37 -08002735 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002736 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002737
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002738 Region aboveOpaqueLayers;
2739 Region aboveCoveredLayers;
2740 Region dirty;
2741
Mathias Agopian87baae12012-07-31 12:38:26 -07002742 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002743
Robert Carr2047fae2016-11-28 14:09:09 -08002744 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002745 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002746 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002747
Jesse Hall01e29052013-02-19 16:13:35 -08002748 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002749 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002750 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002751
Mathias Agopianab028732010-03-16 16:41:46 -07002752 /*
2753 * opaqueRegion: area of a surface that is fully opaque.
2754 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002755 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002756
2757 /*
2758 * visibleRegion: area of a surface that is visible on screen
2759 * and not fully transparent. This is essentially the layer's
2760 * footprint minus the opaque regions above it.
2761 * Areas covered by a translucent surface are considered visible.
2762 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002763 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002764
2765 /*
2766 * coveredRegion: area of a surface that is covered by all
2767 * visible regions above it (which includes the translucent areas).
2768 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002769 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002770
Jesse Halla8026d22012-09-25 13:25:04 -07002771 /*
2772 * transparentRegion: area of a surface that is hinted to be completely
2773 * transparent. This is only used to tell when the layer has no visible
2774 * non-transparent regions and can be removed from the layer list. It
2775 * does not affect the visibleRegion of this layer or any layers
2776 * beneath it. The hint may not be correct if apps don't respect the
2777 * SurfaceView restrictions (which, sadly, some don't).
2778 */
2779 Region transparentRegion;
2780
Mathias Agopianab028732010-03-16 16:41:46 -07002781
2782 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002783 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002784 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002785 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002786 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002787 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002788 if (!visibleRegion.isEmpty()) {
2789 // Remove the transparent area from the visible region
2790 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002791 if (tr.preserveRects()) {
2792 // transform the transparent region
2793 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002794 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002795 // transformation too complex, can't do the
2796 // transparent region optimization.
2797 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002798 }
Mathias Agopianab028732010-03-16 16:41:46 -07002799 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002800
Mathias Agopianab028732010-03-16 16:41:46 -07002801 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002802 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002803 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002804 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2805 // the opaque region is the layer's footprint
2806 opaqueRegion = visibleRegion;
2807 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002808 }
2809 }
2810
Robert Carre5f4f692018-01-12 13:12:28 -08002811 if (visibleRegion.isEmpty()) {
2812 layer->clearVisibilityRegions();
2813 return;
2814 }
2815
Mathias Agopianab028732010-03-16 16:41:46 -07002816 // Clip the covered region to the visible region
2817 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2818
2819 // Update aboveCoveredLayers for next (lower) layer
2820 aboveCoveredLayers.orSelf(visibleRegion);
2821
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002822 // subtract the opaque region covered by the layers above us
2823 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002824
2825 // compute this layer's dirty region
2826 if (layer->contentDirty) {
2827 // we need to invalidate the whole region
2828 dirty = visibleRegion;
2829 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002830 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002831 layer->contentDirty = false;
2832 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002833 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002834 * the exposed region consists of two components:
2835 * 1) what's VISIBLE now and was COVERED before
2836 * 2) what's EXPOSED now less what was EXPOSED before
2837 *
2838 * note that (1) is conservative, we start with the whole
2839 * visible region but only keep what used to be covered by
2840 * something -- which mean it may have been exposed.
2841 *
2842 * (2) handles areas that were not covered by anything but got
2843 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002844 */
Mathias Agopianab028732010-03-16 16:41:46 -07002845 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002846 const Region oldVisibleRegion = layer->visibleRegion;
2847 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002848 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2849 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002850 }
2851 dirty.subtractSelf(aboveOpaqueLayers);
2852
2853 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002854 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002855
Mathias Agopianab028732010-03-16 16:41:46 -07002856 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002857 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002858
Jesse Halla8026d22012-09-25 13:25:04 -07002859 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002860 layer->setVisibleRegion(visibleRegion);
2861 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002862 layer->setVisibleNonTransparentRegion(
2863 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002864 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002865
Mathias Agopian87baae12012-07-31 12:38:26 -07002866 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002867}
2868
Chia-I Wuab0c3192017-08-01 11:29:00 -07002869void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002870 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002871 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002872 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002873 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002874 }
2875 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002876}
2877
Dan Stoza6b9454d2014-11-07 16:00:59 -08002878bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002879{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002880 ALOGV("handlePageFlip");
2881
Brian Andersond6927fb2016-07-23 23:37:30 -07002882 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002883
Mathias Agopian4fec8732012-06-29 14:12:52 -07002884 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002885 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002886 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002887
2888 // Store the set of layers that need updates. This set must not change as
2889 // buffers are being latched, as this could result in a deadlock.
2890 // Example: Two producers share the same command stream and:
2891 // 1.) Layer 0 is latched
2892 // 2.) Layer 0 gets a new frame
2893 // 2.) Layer 1 gets a new frame
2894 // 3.) Layer 1 is latched.
2895 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2896 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002897 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002898 if (layer->hasQueuedFrame()) {
2899 frameQueued = true;
2900 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002901 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002902 } else {
2903 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002904 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002905 } else {
2906 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002907 }
Robert Carr2047fae2016-11-28 14:09:09 -08002908 });
2909
Dan Stoza9e56aa02015-11-02 13:00:03 -08002910 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002911 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002912 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002913 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002914 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002915 newDataLatched = true;
2916 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002917 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002918
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002919 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002920
2921 // If we will need to wake up at some time in the future to deal with a
2922 // queued frame that shouldn't be displayed during this vsync period, wake
2923 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002924 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002925 signalLayerUpdate();
2926 }
2927
2928 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002929 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002930}
2931
Mathias Agopianad456f92011-01-13 17:53:01 -08002932void SurfaceFlinger::invalidateHwcGeometry()
2933{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002934 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002935}
2936
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002937
Fabien Sanglard830b8472016-11-30 16:35:58 -08002938void SurfaceFlinger::doDisplayComposition(
2939 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002940 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002941{
Dan Stoza71433162014-02-04 16:22:36 -08002942 // We only need to actually compose the display if:
2943 // 1) It is being handled by hardware composer, which may need this to
2944 // keep its virtual display state machine in sync, or
2945 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002946 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002947 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002948 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002949 return;
2950 }
2951
Dan Stoza9e56aa02015-11-02 13:00:03 -08002952 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002953 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002954
2955 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002956 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002957}
2958
Chia-I Wub02087d2017-11-09 10:19:54 -08002959bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002960{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002961 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002962
Chia-I Wub02087d2017-11-09 10:19:54 -08002963 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002964 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002965 const auto hwcId = displayDevice->getHwcDisplayId();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002966 const bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002967 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002968
Chia-I Wu8e50e692018-05-04 10:12:37 -07002969 bool applyColorMatrix = false;
2970 bool applyLegacyColorMatrix = false;
2971 mat4 colorMatrix;
2972 mat4 legacyColorMatrix;
2973 const mat4* currentColorMatrix = nullptr;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002974
Dan Stoza9e56aa02015-11-02 13:00:03 -08002975 if (hasClientComposition) {
2976 ALOGV("hasClientComposition");
2977
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002978 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002979 if (displayDevice->hasWideColorGamut()) {
2980 outputDataspace = displayDevice->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002981 }
2982 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002983 getBE().mRenderEngine->setDisplayMaxLuminance(
2984 displayDevice->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002985
Chia-I Wu8e50e692018-05-04 10:12:37 -07002986 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
2987 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2988 HWC2::Capability::SkipClientColorTransform);
2989
2990 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2991 if (applyColorMatrix) {
2992 colorMatrix = mDrawingState.colorMatrix;
2993 }
2994
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002995 applyLegacyColorMatrix = (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
2996 outputDataspace != Dataspace::UNKNOWN &&
2997 outputDataspace != Dataspace::SRGB);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002998 if (applyLegacyColorMatrix) {
2999 if (applyColorMatrix) {
3000 legacyColorMatrix = colorMatrix * mLegacySrgbSaturationMatrix;
3001 } else {
3002 legacyColorMatrix = mLegacySrgbSaturationMatrix;
3003 }
3004 }
3005
Chia-I Wu7f402902017-11-09 12:51:10 -08003006 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003007 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskibf170d92018-04-19 15:08:05 -07003008 displayDevice->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08003009 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003010
3011 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08003012 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07003013 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
3014 }
3015 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003016 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003017
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003018 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003019 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003020 // when using overlays, we assume a fully transparent framebuffer
3021 // NOTE: we could reduce how much we need to clear, for instance
3022 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003023 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003024 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003025 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003026 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003027 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003028 // we're left with the letterbox region
3029 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08003030 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07003031
3032 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08003033 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07003034
Mathias Agopianb9494d52012-04-18 02:28:45 -07003035 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003036 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003037 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08003038 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003039 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003040 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003041
Dominik Laskowski281644e2018-04-19 15:47:35 -07003042 if (!displayDevice->isPrimary()) {
Mathias Agopian766dc492012-10-30 18:08:06 -07003043 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07003044 // scissor on the main display. It should never be needed
3045 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08003046 const Rect& bounds(displayDevice->getBounds());
3047 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003048 if (scissor != bounds) {
3049 // scissor doesn't match the screen's dimensions, so we
3050 // need to clear everything outside of it and enable
3051 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003052
Mathias Agopianf45c5102012-10-24 16:29:17 -07003053 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08003054 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08003055 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07003056 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003057 }
3058 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003059 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003060
Mathias Agopian85d751c2012-08-29 16:59:24 -07003061 /*
3062 * and then, render the layers targeted at the framebuffer
3063 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003064
Dan Stoza9e56aa02015-11-02 13:00:03 -08003065 ALOGV("Rendering client layers");
3066 const Transform& displayTransform = displayDevice->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003067 bool firstLayer = true;
3068 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
3069 const Region clip(bounds.intersect(
3070 displayTransform.transform(layer->visibleRegion)));
3071 ALOGV("Layer: %s", layer->getName().string());
3072 ALOGV(" Composition type: %s",
3073 to_string(layer->getCompositionType(hwcId)).c_str());
3074 if (!clip.isEmpty()) {
3075 switch (layer->getCompositionType(hwcId)) {
3076 case HWC2::Composition::Cursor:
3077 case HWC2::Composition::Device:
3078 case HWC2::Composition::Sideband:
3079 case HWC2::Composition::SolidColor: {
3080 const Layer::State& state(layer->getDrawingState());
3081 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
3082 layer->isOpaque(state) && (state.color.a == 1.0f)
3083 && hasClientComposition) {
3084 // never clear the very first layer since we're
3085 // guaranteed the FB is already cleared
3086 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003087 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003088 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003089 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003090 case HWC2::Composition::Client: {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003091 // switch color matrices lazily
3092 if (layer->isLegacyDataSpace()) {
Chia-I Wud56c39a2018-05-07 15:24:43 -07003093 // TODO(b/78891890) Legacy sRGB saturation matrix should be set
3094 // separately.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003095 if (applyLegacyColorMatrix && currentColorMatrix != &legacyColorMatrix) {
3096 getRenderEngine().setupColorTransform(legacyColorMatrix);
3097 currentColorMatrix = &legacyColorMatrix;
3098 }
3099 } else {
3100 if (applyColorMatrix && currentColorMatrix != &colorMatrix) {
3101 getRenderEngine().setupColorTransform(colorMatrix);
3102 currentColorMatrix = &colorMatrix;
3103 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003104 }
Chia-I Wu8e50e692018-05-04 10:12:37 -07003105
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003106 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003107 break;
3108 }
3109 default:
3110 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003111 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003112 } else {
3113 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003114 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003115 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003116 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003117
Chia-I Wu8e50e692018-05-04 10:12:37 -07003118 if (applyColorMatrix || applyLegacyColorMatrix) {
3119 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003120 }
3121
Mathias Agopianf45c5102012-10-24 16:29:17 -07003122 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003123 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003124 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003125}
3126
Fabien Sanglard830b8472016-11-30 16:35:58 -08003127void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
3128 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003129 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003130 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003131}
3132
Dan Stoza7d89d062015-04-30 13:29:25 -07003133status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003134 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003135 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003136 const sp<Layer>& lbc,
3137 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003138{
Dan Stoza7d89d062015-04-30 13:29:25 -07003139 // add this layer to the current state list
3140 {
3141 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003142 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003143 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3144 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003145 return NO_MEMORY;
3146 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003147 if (parent == nullptr) {
3148 mCurrentState.layersSortedByZ.add(lbc);
3149 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003150 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003151 ALOGE("addClientLayer called with a removed parent");
3152 return NAME_NOT_FOUND;
3153 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003154 parent->addChild(lbc);
3155 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003156
Dan Stoza101d8dc2018-02-27 15:42:25 -08003157 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
Dan Stoza0a0158c2018-03-16 13:38:54 -07003158 // TODO (b/74616334): Change this back to a fatal assert once the leak is fixed
3159 ALOGE_IF(mGraphicBufferProducerList.size() > mMaxGraphicBufferProducerListSize,
3160 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3161 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize,
3162 mNumLayers);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003163 mLayersAdded = true;
3164 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003165 }
3166
Mathias Agopian96f08192010-06-02 23:28:45 -07003167 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003168 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003169
Dan Stoza7d89d062015-04-30 13:29:25 -07003170 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003171}
3172
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003173status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003174 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003175 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3176}
Robert Carr7f9b8992017-03-10 11:08:39 -08003177
chaviwca27f252018-02-06 16:46:39 -08003178status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3179 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003180 if (layer->isPendingRemoval()) {
3181 return NO_ERROR;
3182 }
3183
Robert Carr1f0a16a2016-10-24 16:27:39 -07003184 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003185 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003186 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003187 if (topLevelOnly) {
3188 return NO_ERROR;
3189 }
3190
Chia-I Wu98f1c102017-05-30 14:54:08 -07003191 sp<Layer> ancestor = p;
3192 while (ancestor->getParent() != nullptr) {
3193 ancestor = ancestor->getParent();
3194 }
3195 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3196 ALOGE("removeLayer called with a layer whose parent has been removed");
3197 return NAME_NOT_FOUND;
3198 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003199
3200 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003201 } else {
3202 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003203 }
3204
Robert Carr136e2f62017-02-08 17:54:29 -08003205 // As a matter of normal operation, the LayerCleaner will produce a second
3206 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3207 // so we will succeed in promoting it, but it's already been removed
3208 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3209 // otherwise something has gone wrong and we are leaking the layer.
3210 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003211 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3212 layer->getName().string(),
3213 (p != nullptr) ? p->getName().string() : "no-parent");
3214 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003215 } else if (index < 0) {
3216 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003217 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003218
Chia-I Wuc6657022017-08-15 11:18:17 -07003219 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003220 mLayersPendingRemoval.add(layer);
3221 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003222 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003223 setTransactionFlags(eTransactionNeeded);
3224 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003225}
3226
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003227uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003228 return android_atomic_release_load(&mTransactionFlags);
3229}
3230
Mathias Agopian3f844832013-08-07 21:24:32 -07003231uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003232 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3233}
3234
Mathias Agopian3f844832013-08-07 21:24:32 -07003235uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003236 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3237}
3238
3239uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3240 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003241 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003242 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003243 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003244 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003245 }
3246 return old;
3247}
3248
chaviwca27f252018-02-06 16:46:39 -08003249bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3250 for (const ComposerState& state : states) {
3251 // Here we need to check that the interface we're given is indeed
3252 // one of our own. A malicious client could give us a nullptr
3253 // IInterface, or one of its own or even one of our own but a
3254 // different type. All these situations would cause us to crash.
3255 if (state.client == nullptr) {
3256 return true;
3257 }
3258
3259 sp<IBinder> binder = IInterface::asBinder(state.client);
3260 if (binder == nullptr) {
3261 return true;
3262 }
3263
3264 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3265 return true;
3266 }
3267 }
3268 return false;
3269}
3270
Mathias Agopian8b33f032012-07-24 20:43:54 -07003271void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003272 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003273 const Vector<DisplayState>& displays,
3274 uint32_t flags)
3275{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003276 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003277 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003278 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003279
chaviwca27f252018-02-06 16:46:39 -08003280 if (containsAnyInvalidClientState(states)) {
3281 return;
3282 }
3283
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003284 if (flags & eAnimation) {
3285 // For window updates that are part of an animation we must wait for
3286 // previous animation "frames" to be handled.
3287 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003288 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003289 if (CC_UNLIKELY(err != NO_ERROR)) {
3290 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003291 // caller after a few seconds.
3292 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3293 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003294 mAnimTransactionPending = false;
3295 break;
3296 }
3297 }
3298 }
3299
chaviwca27f252018-02-06 16:46:39 -08003300 for (const DisplayState& display : displays) {
3301 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003302 }
3303
chaviwca27f252018-02-06 16:46:39 -08003304 for (const ComposerState& state : states) {
3305 transactionFlags |= setClientStateLocked(state);
3306 }
3307
3308 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3309 // as destroyed should only occur after setting all other states. This is to allow for a
3310 // child re-parent to happen before marking its original parent as destroyed (which would
3311 // then mark the child as destroyed).
3312 for (const ComposerState& state : states) {
3313 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003314 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003315
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003316 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3317 // anyway. This can be used as a flush mechanism for previous async transactions.
3318 // Empty animation transaction can be used to simulate back-pressure, so also force a
3319 // transaction for empty animation transactions.
3320 if (transactionFlags == 0 &&
3321 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003322 transactionFlags = eTransactionNeeded;
3323 }
3324
Mathias Agopian386aa982011-11-07 21:58:03 -08003325 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003326 if (mInterceptor->isEnabled()) {
3327 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003328 }
Irvel468051e2016-06-13 16:44:44 -07003329
Mathias Agopian386aa982011-11-07 21:58:03 -08003330 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003331 const auto start = (flags & eEarlyWakeup)
3332 ? VSyncModulator::TransactionStart::EARLY
3333 : VSyncModulator::TransactionStart::NORMAL;
3334 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003335
3336 // if this is a synchronous transaction, wait for it to take effect
3337 // before returning.
3338 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003339 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003340 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003341 if (flags & eAnimation) {
3342 mAnimTransactionPending = true;
3343 }
3344 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003345 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3346 if (CC_UNLIKELY(err != NO_ERROR)) {
3347 // just in case something goes wrong in SF, return to the
3348 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003349 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3350 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003351 break;
3352 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003353 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003354 }
3355}
3356
Mathias Agopiane57f2922012-08-09 16:29:12 -07003357uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3358{
Jesse Hall9a143922012-10-04 16:29:19 -07003359 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3360 if (dpyIdx < 0)
3361 return 0;
3362
Mathias Agopiane57f2922012-08-09 16:29:12 -07003363 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003364 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003365 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003366 const uint32_t what = s.what;
3367 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003368 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003369 disp.surface = s.surface;
3370 flags |= eDisplayTransactionNeeded;
3371 }
3372 }
3373 if (what & DisplayState::eLayerStackChanged) {
3374 if (disp.layerStack != s.layerStack) {
3375 disp.layerStack = s.layerStack;
3376 flags |= eDisplayTransactionNeeded;
3377 }
3378 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003379 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003380 if (disp.orientation != s.orientation) {
3381 disp.orientation = s.orientation;
3382 flags |= eDisplayTransactionNeeded;
3383 }
3384 if (disp.frame != s.frame) {
3385 disp.frame = s.frame;
3386 flags |= eDisplayTransactionNeeded;
3387 }
3388 if (disp.viewport != s.viewport) {
3389 disp.viewport = s.viewport;
3390 flags |= eDisplayTransactionNeeded;
3391 }
3392 }
Michael Lentine47e45402014-07-18 15:34:25 -07003393 if (what & DisplayState::eDisplaySizeChanged) {
3394 if (disp.width != s.width) {
3395 disp.width = s.width;
3396 flags |= eDisplayTransactionNeeded;
3397 }
3398 if (disp.height != s.height) {
3399 disp.height = s.height;
3400 flags |= eDisplayTransactionNeeded;
3401 }
3402 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003403 }
3404 return flags;
3405}
3406
chaviwca27f252018-02-06 16:46:39 -08003407uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3408 const layer_state_t& s = composerState.state;
3409 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3410
Mathias Agopian13127d82013-03-05 17:47:11 -08003411 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003412 if (layer == nullptr) {
3413 return 0;
3414 }
3415
3416 if (layer->isPendingRemoval()) {
3417 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3418 return 0;
3419 }
3420
3421 uint32_t flags = 0;
3422
3423 const uint32_t what = s.what;
3424 bool geometryAppliesWithResize =
3425 what & layer_state_t::eGeometryAppliesWithResize;
3426 if (what & layer_state_t::ePositionChanged) {
3427 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3428 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003429 }
chaviw8b3871a2017-11-01 17:41:01 -07003430 }
3431 if (what & layer_state_t::eLayerChanged) {
3432 // NOTE: index needs to be calculated before we update the state
3433 const auto& p = layer->getParent();
3434 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003435 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003436 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003437 mCurrentState.layersSortedByZ.removeAt(idx);
3438 mCurrentState.layersSortedByZ.add(layer);
3439 // we need traversal (state changed)
3440 // AND transaction (list changed)
3441 flags |= eTransactionNeeded|eTraversalNeeded;
3442 }
chaviw8b3871a2017-11-01 17:41:01 -07003443 } else {
3444 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003445 flags |= eTransactionNeeded|eTraversalNeeded;
3446 }
3447 }
chaviw8b3871a2017-11-01 17:41:01 -07003448 }
3449 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003450 // NOTE: index needs to be calculated before we update the state
3451 const auto& p = layer->getParent();
3452 if (p == nullptr) {
3453 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3454 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3455 mCurrentState.layersSortedByZ.removeAt(idx);
3456 mCurrentState.layersSortedByZ.add(layer);
3457 // we need traversal (state changed)
3458 // AND transaction (list changed)
3459 flags |= eTransactionNeeded|eTraversalNeeded;
3460 }
3461 } else {
3462 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3463 flags |= eTransactionNeeded|eTraversalNeeded;
3464 }
chaviw8b3871a2017-11-01 17:41:01 -07003465 }
3466 }
3467 if (what & layer_state_t::eSizeChanged) {
3468 if (layer->setSize(s.w, s.h)) {
3469 flags |= eTraversalNeeded;
3470 }
3471 }
3472 if (what & layer_state_t::eAlphaChanged) {
3473 if (layer->setAlpha(s.alpha))
3474 flags |= eTraversalNeeded;
3475 }
3476 if (what & layer_state_t::eColorChanged) {
3477 if (layer->setColor(s.color))
3478 flags |= eTraversalNeeded;
3479 }
3480 if (what & layer_state_t::eMatrixChanged) {
3481 if (layer->setMatrix(s.matrix))
3482 flags |= eTraversalNeeded;
3483 }
3484 if (what & layer_state_t::eTransparentRegionChanged) {
3485 if (layer->setTransparentRegionHint(s.transparentRegion))
3486 flags |= eTraversalNeeded;
3487 }
3488 if (what & layer_state_t::eFlagsChanged) {
3489 if (layer->setFlags(s.flags, s.mask))
3490 flags |= eTraversalNeeded;
3491 }
3492 if (what & layer_state_t::eCropChanged) {
3493 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3494 flags |= eTraversalNeeded;
3495 }
3496 if (what & layer_state_t::eFinalCropChanged) {
3497 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3498 flags |= eTraversalNeeded;
3499 }
3500 if (what & layer_state_t::eLayerStackChanged) {
3501 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3502 // We only allow setting layer stacks for top level layers,
3503 // everything else inherits layer stack from its parent.
3504 if (layer->hasParent()) {
3505 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3506 layer->getName().string());
3507 } else if (idx < 0) {
3508 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3509 "that also does not appear in the top level layer list. Something"
3510 " has gone wrong.", layer->getName().string());
3511 } else if (layer->setLayerStack(s.layerStack)) {
3512 mCurrentState.layersSortedByZ.removeAt(idx);
3513 mCurrentState.layersSortedByZ.add(layer);
3514 // we need traversal (state changed)
3515 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003516 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003517 }
3518 }
3519 if (what & layer_state_t::eDeferTransaction) {
3520 if (s.barrierHandle != nullptr) {
3521 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3522 } else if (s.barrierGbp != nullptr) {
3523 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3524 if (authenticateSurfaceTextureLocked(gbp)) {
3525 const auto& otherLayer =
3526 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3527 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3528 } else {
3529 ALOGE("Attempt to defer transaction to to an"
3530 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003531 }
3532 }
chaviw8b3871a2017-11-01 17:41:01 -07003533 // We don't trigger a traversal here because if no other state is
3534 // changed, we don't want this to cause any more work
3535 }
3536 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003537 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003538 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003539 if (!hadParent) {
3540 mCurrentState.layersSortedByZ.remove(layer);
3541 }
chaviw8b3871a2017-11-01 17:41:01 -07003542 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003543 }
chaviw8b3871a2017-11-01 17:41:01 -07003544 }
3545 if (what & layer_state_t::eReparentChildren) {
3546 if (layer->reparentChildren(s.reparentHandle)) {
3547 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003548 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003549 }
chaviw8b3871a2017-11-01 17:41:01 -07003550 if (what & layer_state_t::eDetachChildren) {
3551 layer->detachChildren();
3552 }
3553 if (what & layer_state_t::eOverrideScalingModeChanged) {
3554 layer->setOverrideScalingMode(s.overrideScalingMode);
3555 // We don't trigger a traversal here because if no other state is
3556 // changed, we don't want this to cause any more work
3557 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003558 return flags;
3559}
3560
chaviwca27f252018-02-06 16:46:39 -08003561void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3562 const layer_state_t& state = composerState.state;
3563 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3564
3565 sp<Layer> layer(client->getLayerUser(state.surface));
3566 if (layer == nullptr) {
3567 return;
3568 }
3569
3570 if (layer->isPendingRemoval()) {
3571 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3572 return;
3573 }
3574
3575 if (state.what & layer_state_t::eDestroySurface) {
3576 removeLayerLocked(mStateLock, layer);
3577 }
3578}
3579
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003580status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003581 const String8& name,
3582 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003583 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003584 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003585 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003586{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003587 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003588 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003589 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003590 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003591 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003592
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003593 status_t result = NO_ERROR;
3594
3595 sp<Layer> layer;
3596
Cody Northropbc755282017-03-31 12:00:08 -06003597 String8 uniqueName = getUniqueLayerName(name);
3598
Mathias Agopian3165cc22012-08-08 19:42:09 -07003599 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3600 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003601 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003602 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003603 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003604
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003605 break;
chaviw13fdc492017-06-27 12:40:18 -07003606 case ISurfaceComposerClient::eFXSurfaceColor:
3607 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003608 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003609 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003610 break;
3611 default:
3612 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003613 break;
3614 }
3615
Dan Stoza7d89d062015-04-30 13:29:25 -07003616 if (result != NO_ERROR) {
3617 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003618 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003619
Chia-I Wuab0c3192017-08-01 11:29:00 -07003620 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3621 // TODO b/64227542
3622 if (windowType == 441731) {
3623 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3624 layer->setPrimaryDisplayOnly();
3625 }
3626
Albert Chaulk479c60c2017-01-27 14:21:34 -05003627 layer->setInfo(windowType, ownerUid);
3628
Robert Carr1f0a16a2016-10-24 16:27:39 -07003629 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003630 if (result != NO_ERROR) {
3631 return result;
3632 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003633 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003634
3635 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003636 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003637}
3638
Cody Northropbc755282017-03-31 12:00:08 -06003639String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3640{
3641 bool matchFound = true;
3642 uint32_t dupeCounter = 0;
3643
3644 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3645 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3646
3647 // Loop over layers until we're sure there is no matching name
3648 while (matchFound) {
3649 matchFound = false;
3650 mDrawingState.traverseInZOrder([&](Layer* layer) {
3651 if (layer->getName() == uniqueName) {
3652 matchFound = true;
3653 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3654 }
3655 });
3656 }
3657
3658 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3659
3660 return uniqueName;
3661}
3662
David Sodman0c69cad2017-08-21 12:12:51 -07003663status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003664 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3665 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003666{
3667 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003668 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003669 case PIXEL_FORMAT_TRANSPARENT:
3670 case PIXEL_FORMAT_TRANSLUCENT:
3671 format = PIXEL_FORMAT_RGBA_8888;
3672 break;
3673 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003674 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003675 break;
3676 }
3677
David Sodman0c69cad2017-08-21 12:12:51 -07003678 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3679 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003680 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003681 *handle = layer->getHandle();
3682 *gbp = layer->getProducer();
3683 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003684 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003685
David Sodman0c69cad2017-08-21 12:12:51 -07003686 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003687 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003688}
3689
chaviw13fdc492017-06-27 12:40:18 -07003690status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003691 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003692 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003693{
chaviw13fdc492017-06-27 12:40:18 -07003694 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003695 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003696 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003697}
3698
Mathias Agopianac9fa422013-02-11 16:40:36 -08003699status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003700{
Robert Carr9524cb32017-02-13 11:32:32 -08003701 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003702 status_t err = NO_ERROR;
3703 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003704 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003705 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003706 err = removeLayer(l);
3707 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3708 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003709 }
3710 return err;
3711}
3712
Mathias Agopian13127d82013-03-05 17:47:11 -08003713status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003714{
Mathias Agopian67106042013-03-14 19:18:13 -07003715 // called by ~LayerCleaner() when all references to the IBinder (handle)
3716 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003717 sp<Layer> l = layer.promote();
3718 if (l == nullptr) {
3719 // The layer has already been removed, carry on
3720 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003721 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003722 // If we have a parent, then we can continue to live as long as it does.
3723 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003724}
3725
Mathias Agopianb60314a2012-04-10 22:09:54 -07003726// ---------------------------------------------------------------------------
3727
Andy McFadden13a082e2012-08-24 10:16:42 -07003728void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003729 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003730 Vector<ComposerState> state;
3731 Vector<DisplayState> displays;
3732 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003733 d.what = DisplayState::eDisplayProjectionChanged |
3734 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003735 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003736 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003737 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003738 d.frame.makeInvalid();
3739 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003740 d.width = 0;
3741 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003742 displays.add(d);
3743 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003744 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3745 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003746
David Sodman105b7dc2017-11-04 20:28:14 -07003747 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003748 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003749 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003750
Brian Andersond0010582017-03-07 13:20:31 -08003751 // Use phase of 0 since phase is not known.
3752 // Use latency of 0, which will snap to the ideal latency.
3753 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003754}
3755
3756void SurfaceFlinger::initializeDisplays() {
3757 class MessageScreenInitialized : public MessageBase {
3758 SurfaceFlinger* flinger;
3759 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003760 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003761 virtual bool handler() {
3762 flinger->onInitializeDisplays();
3763 return true;
3764 }
3765 };
3766 sp<MessageBase> msg = new MessageScreenInitialized(this);
3767 postMessageAsync(msg); // we may be called from main thread, use async message
3768}
3769
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003770void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003771 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003772 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3773 this);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003774 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);
Dominik Laskowski281644e2018-04-19 15:47:35 -07003781 if (hw->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003782 ALOGW("Trying to set power mode for virtual display");
3783 return;
3784 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003785
Lloyd Pique4dccc412018-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 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003793 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003794 }
3795
Dominik Laskowski281644e2018-04-19 15:47:35 -07003796 int32_t type = hw->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003797 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003798 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003799 getHwComposer().setPowerMode(type, mode);
Dominik Laskowski281644e2018-04-19 15:47:35 -07003800 if (hw->isPrimary() && 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
Dominik Laskowski281644e2018-04-19 15:47:35 -07003822 if (hw->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003823 disableHardwareVsync(true); // also cancels any in-progress resync
3824
Mathias Agopiancde87a32012-09-13 14:09:01 -07003825 // FIXME: eventthread only knows about the main display right now
3826 mEventThread->onScreenReleased();
3827 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003828
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003829 getHwComposer().setPowerMode(type, mode);
3830 mVisibleRegionsDirty = true;
3831 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003832 } else if (mode == HWC_POWER_MODE_DOZE ||
3833 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003834 // Update display while dozing
3835 getHwComposer().setPowerMode(type, mode);
Dominik Laskowski281644e2018-04-19 15:47:35 -07003836 if (hw->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003837 // FIXME: eventthread only knows about the main display right now
3838 mEventThread->onScreenAcquired();
3839 resyncToHardwareVsync(true);
3840 }
3841 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3842 // Leave display going to doze
Dominik Laskowski281644e2018-04-19 15:47:35 -07003843 if (hw->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003844 disableHardwareVsync(true); // also cancels any in-progress resync
3845 // FIXME: eventthread only knows about the main display right now
3846 mEventThread->onScreenReleased();
3847 }
3848 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003849 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003850 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003851 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003852 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003853 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003854}
3855
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003856void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3857 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003858 SurfaceFlinger& mFlinger;
3859 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003860 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003861 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003862 MessageSetPowerMode(SurfaceFlinger& flinger,
3863 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3864 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003865 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003866 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003867 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003868 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003869 mMode, mDisplay.get());
Dominik Laskowski281644e2018-04-19 15:47:35 -07003870 } else if (hw->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003871 ALOGW("Attempt to set power mode = %d for virtual display",
3872 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003873 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003874 mFlinger.setPowerModeInternal(
3875 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003876 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003877 return true;
3878 }
3879 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003880 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003881 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003882}
3883
3884// ---------------------------------------------------------------------------
3885
Lloyd Pique755e3192018-01-31 16:46:15 -08003886status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3887 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003888 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003889
Mathias Agopianbd115332013-04-18 16:41:04 -07003890 IPCThreadState* ipc = IPCThreadState::self();
3891 const int pid = ipc->getCallingPid();
3892 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003893
Mathias Agopianbd115332013-04-18 16:41:04 -07003894 if ((uid != AID_SHELL) &&
3895 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003896 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003897 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003898 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003899 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003900 // (this would indicate SF is stuck, but we want to be able to
3901 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003902 status_t err = mStateLock.timedLock(s2ns(1));
3903 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003904 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003905 result.appendFormat(
3906 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3907 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003908 }
3909
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003910 bool dumpAll = true;
3911 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003912 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003913
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003914 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003915 if ((index < numArgs) &&
3916 (args[index] == String16("--list"))) {
3917 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003918 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003919 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003920 }
3921
3922 if ((index < numArgs) &&
3923 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003924 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003925 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003926 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003927 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003928
3929 if ((index < numArgs) &&
3930 (args[index] == String16("--latency-clear"))) {
3931 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003932 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003933 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003934 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003935
3936 if ((index < numArgs) &&
3937 (args[index] == String16("--dispsync"))) {
3938 index++;
3939 mPrimaryDispSync.dump(result);
3940 dumpAll = false;
3941 }
Dan Stozab90cf072015-03-05 11:05:59 -08003942
3943 if ((index < numArgs) &&
3944 (args[index] == String16("--static-screen"))) {
3945 index++;
3946 dumpStaticScreenStats(result);
3947 dumpAll = false;
3948 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003949
3950 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003951 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003952 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003953 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003954 dumpAll = false;
3955 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003956
3957 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3958 index++;
3959 dumpWideColorInfo(result);
3960 dumpAll = false;
3961 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003962
3963 if ((index < numArgs) &&
3964 (args[index] == String16("--enable-layer-stats"))) {
3965 index++;
3966 mLayerStats.enable();
3967 dumpAll = false;
3968 }
3969
3970 if ((index < numArgs) &&
3971 (args[index] == String16("--disable-layer-stats"))) {
3972 index++;
3973 mLayerStats.disable();
3974 dumpAll = false;
3975 }
3976
3977 if ((index < numArgs) &&
3978 (args[index] == String16("--clear-layer-stats"))) {
3979 index++;
3980 mLayerStats.clear();
3981 dumpAll = false;
3982 }
3983
3984 if ((index < numArgs) &&
3985 (args[index] == String16("--dump-layer-stats"))) {
3986 index++;
3987 mLayerStats.dump(result);
3988 dumpAll = false;
3989 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07003990
3991 if ((index < numArgs) &&
3992 (args[index] == String16("--display-identification"))) {
3993 index++;
3994 dumpDisplayIdentificationData(result);
3995 dumpAll = false;
3996 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003997
3998 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3999 index++;
4000 mTimeStats.parseArgs(asProto, args, index, result);
4001 dumpAll = false;
4002 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004003 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004004
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004005 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004006 if (asProto) {
4007 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4008 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4009 } else {
4010 dumpAllLocked(args, index, result);
4011 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004012 }
4013
Mathias Agopian9795c422009-08-26 16:36:26 -07004014 if (locked) {
4015 mStateLock.unlock();
4016 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004017 }
4018 write(fd, result.string(), result.size());
4019 return NO_ERROR;
4020}
4021
Dan Stozac7014012014-02-14 15:03:43 -08004022void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4023 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004024{
Robert Carr2047fae2016-11-28 14:09:09 -08004025 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004026 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004027 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004028}
4029
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004030void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004031 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004032{
4033 String8 name;
4034 if (index < args.size()) {
4035 name = String8(args[index]);
4036 index++;
4037 }
4038
David Sodman105b7dc2017-11-04 20:28:14 -07004039 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004040 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08004041 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004042
4043 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004044 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004045 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004046 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004047 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004048 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004049 }
Robert Carr2047fae2016-11-28 14:09:09 -08004050 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004051 }
4052}
4053
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004054void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004055 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004056{
4057 String8 name;
4058 if (index < args.size()) {
4059 name = String8(args[index]);
4060 index++;
4061 }
4062
Robert Carr2047fae2016-11-28 14:09:09 -08004063 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004064 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004065 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004066 }
Robert Carr2047fae2016-11-28 14:09:09 -08004067 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004068
Svetoslavd85084b2014-03-20 10:28:31 -07004069 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004070}
4071
Jamie Gennis6547ff42013-07-16 20:12:42 -07004072// This should only be called from the main thread. Otherwise it would need
4073// the lock and should use mCurrentState rather than mDrawingState.
4074void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004075 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004076 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004077 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004078
4079 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4080}
4081
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004082void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004083{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004084 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004085
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004086 if (isLayerTripleBufferingDisabled())
4087 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004088
4089 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004090 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004091 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004092 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004093 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4094 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004095 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004096}
4097
Dan Stozab90cf072015-03-05 11:05:59 -08004098void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4099{
4100 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004101 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4102 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004103 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004104 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004105 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4106 b + 1, bucketTimeSec, percent);
4107 }
David Sodman4a36e932017-11-07 14:29:47 -08004108 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004109 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004110 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004111 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004112 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004113}
4114
Dan Stozae77c7662016-05-13 11:37:28 -07004115void SurfaceFlinger::recordBufferingStats(const char* layerName,
4116 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004117 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4118 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004119 for (const auto& segment : history) {
4120 if (!segment.usedThirdBuffer) {
4121 stats.twoBufferTime += segment.totalTime;
4122 }
4123 if (segment.occupancyAverage < 1.0f) {
4124 stats.doubleBufferedTime += segment.totalTime;
4125 } else if (segment.occupancyAverage < 2.0f) {
4126 stats.tripleBufferedTime += segment.totalTime;
4127 }
4128 ++stats.numSegments;
4129 stats.totalTime += segment.totalTime;
4130 }
4131}
4132
Brian Andersond6927fb2016-07-23 23:37:30 -07004133void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4134 result.appendFormat("Layer frame timestamps:\n");
4135
4136 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4137 const size_t count = currentLayers.size();
4138 for (size_t i=0 ; i<count ; i++) {
4139 currentLayers[i]->dumpFrameEvents(result);
4140 }
4141}
4142
Dan Stozae77c7662016-05-13 11:37:28 -07004143void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4144 result.append("Buffering stats:\n");
4145 result.append(" [Layer name] <Active time> <Two buffer> "
4146 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004147 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004148 typedef std::tuple<std::string, float, float, float> BufferTuple;
4149 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004150 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004151 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004152 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004153 if (stats.numSegments == 0) {
4154 continue;
4155 }
4156 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4157 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4158 stats.totalTime;
4159 float doubleBufferRatio = static_cast<float>(
4160 stats.doubleBufferedTime) / stats.totalTime;
4161 float tripleBufferRatio = static_cast<float>(
4162 stats.tripleBufferedTime) / stats.totalTime;
4163 sorted.insert({activeTime, {name, twoBufferRatio,
4164 doubleBufferRatio, tripleBufferRatio}});
4165 }
4166 for (const auto& sortedPair : sorted) {
4167 float activeTime = sortedPair.first;
4168 const BufferTuple& values = sortedPair.second;
4169 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4170 std::get<0>(values).c_str(), activeTime,
4171 std::get<1>(values), std::get<2>(values),
4172 std::get<3>(values));
4173 }
4174 result.append("\n");
4175}
4176
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004177void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
4178 for (size_t d = 0; d < mDisplays.size(); d++) {
4179 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4180 const int32_t hwcId = displayDevice->getHwcDisplayId();
4181 const auto displayId = getHwComposer().getHwcDisplayId(hwcId);
4182 if (!displayId) {
4183 continue;
4184 }
4185
4186 result.appendFormat("Display %d: ", hwcId);
4187 uint8_t port;
4188 DisplayIdentificationData data;
4189 if (!getHwComposer().getDisplayIdentificationData(*displayId, &port, &data)) {
4190 result.append("no identification data\n");
4191 continue;
4192 }
4193
4194 if (!isEdid(data)) {
4195 result.append("unknown identification data: ");
4196 for (uint8_t byte : data) {
4197 result.appendFormat("%x ", byte);
4198 }
4199 result.append("\n");
4200 continue;
4201 }
4202
4203 const auto edid = parseEdid(data);
4204 if (!edid) {
4205 result.append("invalid EDID: ");
4206 for (uint8_t byte : data) {
4207 result.appendFormat("%x ", byte);
4208 }
4209 result.append("\n");
4210 continue;
4211 }
4212
4213 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4214 result.append(edid->displayName.data(), edid->displayName.length());
4215 result.append("\"\n");
4216 }
4217 result.append("\n");
4218}
4219
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004220void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4221 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004222 result.appendFormat("DisplayColorSetting: %d\n", mDisplayColorSetting);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004223
4224 // TODO: print out if wide-color mode is active or not
4225
4226 for (size_t d = 0; d < mDisplays.size(); d++) {
4227 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4228 int32_t hwcId = displayDevice->getHwcDisplayId();
4229 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4230 continue;
4231 }
4232
4233 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004234 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004235 for (auto&& mode : modes) {
4236 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4237 }
4238
Peiyong Lina52f0292018-03-14 17:26:31 -07004239 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004240 result.appendFormat(" Current color mode: %s (%d)\n",
4241 decodeColorMode(currentMode).c_str(), currentMode);
4242 }
4243 result.append("\n");
4244}
4245
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004246LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004247 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004248 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4249 const State& state = useDrawing ? mDrawingState : mCurrentState;
4250 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004251 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004252 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004253 });
4254
4255 return layersProto;
4256}
4257
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004258LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4259 LayersProto layersProto;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004260 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004261
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004262 SizeProto* resolution = layersProto.mutable_resolution();
4263 resolution->set_w(displayDevice->getWidth());
4264 resolution->set_h(displayDevice->getHeight());
4265
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004266 layersProto.set_color_mode(decodeColorMode(displayDevice->getActiveColorMode()));
4267 layersProto.set_color_transform(decodeColorTransform(displayDevice->getColorTransform()));
4268 layersProto.set_global_transform(
4269 static_cast<int32_t>(displayDevice->getOrientationTransform()));
4270
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004271 mDrawingState.traverseInZOrder([&](Layer* layer) {
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004272 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004273 LayerProto* layerProto = layersProto.add_layers();
4274 layer->writeToProto(layerProto, hwcId);
4275 }
4276 });
4277
4278 return layersProto;
4279}
4280
Mathias Agopian74d211a2013-04-22 16:55:35 +02004281void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4282 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004283{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004284 bool colorize = false;
4285 if (index < args.size()
4286 && (args[index] == String16("--color"))) {
4287 colorize = true;
4288 index++;
4289 }
4290
4291 Colorizer colorizer(colorize);
4292
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004293 // figure out if we're stuck somewhere
4294 const nsecs_t now = systemTime();
4295 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4296 const nsecs_t inTransaction(mDebugInTransaction);
4297 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4298 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4299
4300 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004301 * Dump library configuration.
4302 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004303
4304 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004305 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004306 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004307 appendSfConfigString(result);
4308 appendUiConfigString(result);
4309 appendGuiConfigString(result);
4310 result.append("\n");
4311
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004312 result.append("\nDisplay identification data:\n");
4313 dumpDisplayIdentificationData(result);
4314
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004315 result.append("\nWide-Color information:\n");
4316 dumpWideColorInfo(result);
4317
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004318 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004319 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004320 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004321 result.append(SyncFeatures::getInstance().toString());
4322 result.append("\n");
4323
David Sodman105b7dc2017-11-04 20:28:14 -07004324 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004325
Andy McFadden41d67d72014-04-25 16:58:34 -07004326 colorizer.bold(result);
4327 result.append("DispSync configuration: ");
4328 colorizer.reset(result);
Dan Stoza84d619e2018-03-28 17:07:36 -07004329 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, early sf phase %" PRId64
4330 " ns, present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4331 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, mVsyncModulator.getEarlyPhaseOffset(),
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004332 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004333 result.append("\n");
4334
Dan Stozab90cf072015-03-05 11:05:59 -08004335 // Dump static screen stats
4336 result.append("\n");
4337 dumpStaticScreenStats(result);
4338 result.append("\n");
4339
Dan Stozae77c7662016-05-13 11:37:28 -07004340 dumpBufferingStats(result);
4341
Andy McFadden4803b742012-09-24 19:07:20 -07004342 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004343 * Dump the visible layer list
4344 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004345 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004346 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004347 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4348 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004349 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004350
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004351 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004352 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004353 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004354 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004355
4356 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004357 * Dump Display state
4358 */
4359
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004360 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004361 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004362 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004363 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4364 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004365 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004366 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004367 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004368
4369 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004370 * Dump SurfaceFlinger global state
4371 */
4372
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004373 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004374 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004375 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004376
Mathias Agopian888c8222012-08-04 21:10:38 -07004377 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004378 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004379
David Sodmanbc815282017-11-05 18:57:52 -08004380 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004381
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004382 if (hw) {
4383 hw->undefinedRegion.dump(result, "undefinedRegion");
4384 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4385 hw->getOrientation(), hw->isDisplayOn());
4386 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004387 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004388 " last eglSwapBuffers() time: %f us\n"
4389 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004390 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004391 " refresh-rate : %f fps\n"
4392 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004393 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004394 " gpu_to_cpu_unsupported : %d\n"
4395 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004396 mLastSwapBufferTime/1000.0,
4397 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004398 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004399 1e9 / activeConfig->getVsyncPeriod(),
4400 activeConfig->getDpiX(),
4401 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004402 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004403
Mathias Agopian74d211a2013-04-22 16:55:35 +02004404 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004405 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004406
Mathias Agopian74d211a2013-04-22 16:55:35 +02004407 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004408 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004409
4410 /*
4411 * VSYNC state
4412 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004413 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004414 result.append("\n");
4415
4416 /*
4417 * HWC layer minidump
4418 */
4419 for (size_t d = 0; d < mDisplays.size(); d++) {
4420 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4421 int32_t hwcId = displayDevice->getHwcDisplayId();
4422 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4423 continue;
4424 }
4425
4426 result.appendFormat("Display %d HWC layers:\n", hwcId);
4427 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004428 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004429 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004430 });
Dan Stozae22aec72016-08-01 13:20:59 -07004431 result.append("\n");
4432 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004433
4434 /*
4435 * Dump HWComposer state
4436 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004437 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004438 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004439 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004440 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004441 result.appendFormat(" h/w composer %s\n",
4442 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004443 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004444
4445 /*
4446 * Dump gralloc state
4447 */
4448 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4449 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004450
4451 /*
4452 * Dump VrFlinger state if in use.
4453 */
4454 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4455 result.append("VrFlinger state:\n");
4456 result.append(mVrFlinger->Dump().c_str());
4457 result.append("\n");
4458 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004459}
4460
Mathias Agopian13127d82013-03-05 17:47:11 -08004461const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004462SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004463 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004464 wp<IBinder> dpy;
4465 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4466 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4467 dpy = mDisplays.keyAt(i);
4468 break;
4469 }
4470 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004471 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004472 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4473 // Just use the primary display so we have something to return
4474 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4475 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004476 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004477}
4478
Keun young Park63f165f2012-08-31 10:53:36 -07004479bool SurfaceFlinger::startDdmConnection()
4480{
4481 void* libddmconnection_dso =
4482 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4483 if (!libddmconnection_dso) {
4484 return false;
4485 }
4486 void (*DdmConnection_start)(const char* name);
4487 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004488 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004489 if (!DdmConnection_start) {
4490 dlclose(libddmconnection_dso);
4491 return false;
4492 }
4493 (*DdmConnection_start)(getServiceName());
4494 return true;
4495}
4496
Chia-I Wu28f320b2018-05-03 11:02:56 -07004497void SurfaceFlinger::updateColorMatrixLocked() {
4498 mat4 colorMatrix;
4499 if (mGlobalSaturationFactor != 1.0f) {
4500 // Rec.709 luma coefficients
4501 float3 luminance{0.213f, 0.715f, 0.072f};
4502 luminance *= 1.0f - mGlobalSaturationFactor;
4503 mat4 saturationMatrix = mat4(
4504 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4505 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4506 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4507 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4508 );
4509 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4510 } else {
4511 colorMatrix = mClientColorMatrix * mDaltonizer();
4512 }
4513
4514 if (mCurrentState.colorMatrix != colorMatrix) {
4515 mCurrentState.colorMatrix = colorMatrix;
4516 mCurrentState.colorMatrixChanged = true;
4517 setTransactionFlags(eTransactionNeeded);
4518 }
4519}
4520
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004521status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004522 switch (code) {
4523 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004524 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004525 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004526 case CLEAR_ANIMATION_FRAME_STATS:
4527 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004528 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004529 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004530 case ENABLE_VSYNC_INJECTIONS:
4531 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004532 {
4533 // codes that require permission check
4534 IPCThreadState* ipc = IPCThreadState::self();
4535 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004536 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004537 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004538 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004539 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004540 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004541 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004542 break;
4543 }
Robert Carr1db73f62016-12-21 12:58:51 -08004544 /*
4545 * Calling setTransactionState is safe, because you need to have been
4546 * granted a reference to Client* and Handle* to do anything with it.
4547 *
4548 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4549 */
4550 case SET_TRANSACTION_STATE:
4551 case CREATE_SCOPED_CONNECTION:
4552 {
4553 return OK;
4554 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004555 case CAPTURE_SCREEN:
4556 {
4557 // codes that require permission check
4558 IPCThreadState* ipc = IPCThreadState::self();
4559 const int pid = ipc->getCallingPid();
4560 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004561 if ((uid != AID_GRAPHICS) &&
4562 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004563 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004564 return PERMISSION_DENIED;
4565 }
4566 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004567 }
chaviwa76b2712017-09-20 12:02:26 -07004568 case CAPTURE_LAYERS: {
4569 IPCThreadState* ipc = IPCThreadState::self();
4570 const int pid = ipc->getCallingPid();
4571 const int uid = ipc->getCallingUid();
4572 if ((uid != AID_GRAPHICS) &&
4573 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4574 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4575 return PERMISSION_DENIED;
4576 }
4577 break;
4578 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004579 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004580 return OK;
4581}
4582
4583status_t SurfaceFlinger::onTransact(
4584 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4585{
4586 status_t credentialCheck = CheckTransactCodeCredentials(code);
4587 if (credentialCheck != OK) {
4588 return credentialCheck;
4589 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004590
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004591 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4592 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004593 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004594 IPCThreadState* ipc = IPCThreadState::self();
4595 const int uid = ipc->getCallingUid();
4596 if (CC_UNLIKELY(uid != AID_SYSTEM
4597 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004598 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004599 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004600 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004601 return PERMISSION_DENIED;
4602 }
4603 int n;
4604 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004605 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004606 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004607 return NO_ERROR;
4608 case 1002: // SHOW_UPDATES
4609 n = data.readInt32();
4610 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004611 invalidateHwcGeometry();
4612 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004613 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004614 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004615 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004616 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004617 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004618 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004619 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004620 setTransactionFlags(
4621 eTransactionNeeded|
4622 eDisplayTransactionNeeded|
4623 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004624 return NO_ERROR;
4625 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004626 case 1006:{ // send empty update
4627 signalRefresh();
4628 return NO_ERROR;
4629 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004630 case 1008: // toggle use of hw composer
4631 n = data.readInt32();
4632 mDebugDisableHWC = n ? 1 : 0;
4633 invalidateHwcGeometry();
4634 repaintEverything();
4635 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004636 case 1009: // toggle use of transform hint
4637 n = data.readInt32();
4638 mDebugDisableTransformHint = n ? 1 : 0;
4639 invalidateHwcGeometry();
4640 repaintEverything();
4641 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004642 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004643 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004644 reply->writeInt32(0);
4645 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004646 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004647 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004648 return NO_ERROR;
4649 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004650 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004651 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004652 return NO_ERROR;
4653 }
4654 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004655 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004656 // daltonize
4657 n = data.readInt32();
4658 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004659 case 1:
4660 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4661 break;
4662 case 2:
4663 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4664 break;
4665 case 3:
4666 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4667 break;
4668 default:
4669 mDaltonizer.setType(ColorBlindnessType::None);
4670 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004671 }
4672 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004673 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004674 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004675 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004676 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004677
4678 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004679 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004680 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004681 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004682 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004683 // apply a color matrix
4684 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004685 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004686 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004687 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004688 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004689 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004690 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004691 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004692 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004693 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004694 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004695
4696 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4697 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004698 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004699 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4700 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4701 }
4702
Chia-I Wu28f320b2018-05-03 11:02:56 -07004703 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004704 return NO_ERROR;
4705 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004706 // This is an experimental interface
4707 // Needs to be shifted to proper binder interface when we productize
4708 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004709 n = data.readInt32();
4710 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004711 return NO_ERROR;
4712 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004713 case 1017: {
4714 n = data.readInt32();
4715 mForceFullDamage = static_cast<bool>(n);
4716 return NO_ERROR;
4717 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004718 case 1018: { // Modify Choreographer's phase offset
4719 n = data.readInt32();
4720 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4721 return NO_ERROR;
4722 }
4723 case 1019: { // Modify SurfaceFlinger's phase offset
4724 n = data.readInt32();
4725 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4726 return NO_ERROR;
4727 }
Irvel468051e2016-06-13 16:44:44 -07004728 case 1020: { // Layer updates interceptor
4729 n = data.readInt32();
4730 if (n) {
4731 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004732 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004733 }
4734 else{
4735 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004736 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004737 }
4738 return NO_ERROR;
4739 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004740 case 1021: { // Disable HWC virtual displays
4741 n = data.readInt32();
4742 mUseHwcVirtualDisplays = !n;
4743 return NO_ERROR;
4744 }
Romain Guy0147a172017-06-01 13:53:56 -07004745 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004746 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004747 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004748
Chia-I Wu28f320b2018-05-03 11:02:56 -07004749 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004750 return NO_ERROR;
4751 }
Romain Guy54f154a2017-10-24 21:40:32 +01004752 case 1023: { // Set native mode
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004753 int32_t value = data.readInt32();
4754 if (value > 2) {
4755 return BAD_VALUE;
4756 }
4757 if (value == 2 && !mBuiltinDisplaySupportsEnhance) {
4758 return BAD_VALUE;
4759 }
Romain Guy54f154a2017-10-24 21:40:32 +01004760
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004761 mDisplayColorSetting = toDisplayColorSetting(value);
Romain Guy54f154a2017-10-24 21:40:32 +01004762 invalidateHwcGeometry();
4763 repaintEverything();
4764 return NO_ERROR;
4765 }
4766 case 1024: { // Is wide color gamut rendering/color management supported?
4767 reply->writeBool(hasWideColorDisplay);
4768 return NO_ERROR;
4769 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004770 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004771 n = data.readInt32();
4772 if (n) {
4773 ALOGV("LayerTracing enabled");
4774 mTracing.enable();
4775 doTracing("tracing.enable");
4776 reply->writeInt32(NO_ERROR);
4777 } else {
4778 ALOGV("LayerTracing disabled");
4779 status_t err = mTracing.disable();
4780 reply->writeInt32(err);
4781 }
4782 return NO_ERROR;
4783 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004784 case 1026: { // Get layer tracing status
4785 reply->writeBool(mTracing.isEnabled());
4786 return NO_ERROR;
4787 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004788 // Is a DisplayColorSetting supported?
4789 case 1027: {
4790 int32_t value = data.readInt32();
4791 switch (value) {
4792 case 0:
4793 reply->writeBool(hasWideColorDisplay);
4794 return NO_ERROR;
4795 case 1:
4796 reply->writeBool(true);
4797 return NO_ERROR;
4798 case 2:
4799 reply->writeBool(mBuiltinDisplaySupportsEnhance);
4800 return NO_ERROR;
4801 default:
4802 return BAD_VALUE;
4803 }
4804 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004805 }
4806 }
4807 return err;
4808}
4809
Steven Thomas6d8110b2017-08-31 18:24:21 -07004810void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004811 android_atomic_or(1, &mRepaintEverything);
4812 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004813}
4814
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004815// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4816class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004817public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004818 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4819 ~WindowDisconnector() {
4820 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004821 }
4822
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004823private:
4824 ANativeWindow* mWindow;
4825 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004826};
4827
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004828status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4829 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4830 int32_t minLayerZ, int32_t maxLayerZ,
4831 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004832 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004833 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004834
chaviwa76b2712017-09-20 12:02:26 -07004835 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4836
4837 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004838 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4839
chaviwa76b2712017-09-20 12:02:26 -07004840 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4841
4842 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4843 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004844 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004845}
4846
4847status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004848 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004849 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004850 ATRACE_CALL();
4851
4852 class LayerRenderArea : public RenderArea {
4853 public:
Robert Carr578038f2018-03-09 12:25:24 -08004854 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4855 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004856 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004857 mLayer(layer),
4858 mCrop(crop),
4859 mFlinger(flinger),
4860 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004861 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004862 Rect getBounds() const override {
4863 const Layer::State& layerState(mLayer->getDrawingState());
4864 return Rect(layerState.active.w, layerState.active.h);
4865 }
4866 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4867 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4868 bool isSecure() const override { return false; }
4869 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004870 Rect getSourceCrop() const override {
4871 if (mCrop.isEmpty()) {
4872 return getBounds();
4873 } else {
4874 return mCrop;
4875 }
4876 }
4877 bool getWideColorSupport() const override { return false; }
4878 Dataspace getDataSpace() const override { return Dataspace::UNKNOWN; }
Peiyong Linfb069302018-04-25 14:34:31 -07004879 float getDisplayMaxLuminance() const override {
4880 return DisplayDevice::sDefaultMaxLumiance;
4881 }
Robert Carr578038f2018-03-09 12:25:24 -08004882
4883 class ReparentForDrawing {
4884 public:
4885 const sp<Layer>& oldParent;
4886 const sp<Layer>& newParent;
4887
4888 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4889 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004890 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004891 }
Robert Carr15eae092018-03-23 13:43:53 -07004892 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004893 };
4894
4895 void render(std::function<void()> drawLayers) override {
4896 if (!mChildrenOnly) {
4897 mTransform = mLayer->getTransform().inverse();
4898 drawLayers();
4899 } else {
4900 Rect bounds = getBounds();
4901 screenshotParentLayer =
4902 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4903 bounds.getWidth(), bounds.getHeight(), 0);
4904
4905 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4906 drawLayers();
4907 }
4908 }
chaviwa76b2712017-09-20 12:02:26 -07004909
chaviwa76b2712017-09-20 12:02:26 -07004910 private:
chaviw7206d492017-11-10 16:16:12 -08004911 const sp<Layer> mLayer;
4912 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004913
4914 // In the "childrenOnly" case we reparent the children to a screenshot
4915 // layer which has no properties set and which does not draw.
4916 sp<ContainerLayer> screenshotParentLayer;
4917 Transform mTransform;
4918
4919 SurfaceFlinger* mFlinger;
4920 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004921 };
4922
4923 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4924 auto parent = layerHandle->owner.promote();
4925
chaviw7206d492017-11-10 16:16:12 -08004926 if (parent == nullptr || parent->isPendingRemoval()) {
4927 ALOGE("captureLayers called with a removed parent");
4928 return NAME_NOT_FOUND;
4929 }
4930
Robert Carr578038f2018-03-09 12:25:24 -08004931 const int uid = IPCThreadState::self()->getCallingUid();
4932 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4933 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4934 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4935 return PERMISSION_DENIED;
4936 }
4937
chaviw7206d492017-11-10 16:16:12 -08004938 Rect crop(sourceCrop);
4939 if (sourceCrop.width() <= 0) {
4940 crop.left = 0;
4941 crop.right = parent->getCurrentState().active.w;
4942 }
4943
4944 if (sourceCrop.height() <= 0) {
4945 crop.top = 0;
4946 crop.bottom = parent->getCurrentState().active.h;
4947 }
4948
4949 int32_t reqWidth = crop.width() * frameScale;
4950 int32_t reqHeight = crop.height() * frameScale;
4951
Robert Carr578038f2018-03-09 12:25:24 -08004952 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004953
Robert Carr578038f2018-03-09 12:25:24 -08004954 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004955 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4956 if (!layer->isVisible()) {
4957 return;
Robert Carr578038f2018-03-09 12:25:24 -08004958 } else if (childrenOnly && layer == parent.get()) {
4959 return;
chaviwa76b2712017-09-20 12:02:26 -07004960 }
4961 visitor(layer);
4962 });
4963 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004964 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004965}
4966
4967status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4968 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004969 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004970 bool useIdentityTransform) {
4971 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004972
chaviwa76b2712017-09-20 12:02:26 -07004973 renderArea.updateDimensions();
4974
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004975 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4976 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4977 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4978 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004979
4980 // This mutex protects syncFd and captureResult for communication of the return values from the
4981 // main thread back to this Binder thread
4982 std::mutex captureMutex;
4983 std::condition_variable captureCondition;
4984 std::unique_lock<std::mutex> captureLock(captureMutex);
4985 int syncFd = -1;
4986 std::optional<status_t> captureResult;
4987
Robert Carr03480e22018-01-04 16:02:06 -08004988 const int uid = IPCThreadState::self()->getCallingUid();
4989 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4990
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004991 sp<LambdaMessage> message = new LambdaMessage([&]() {
4992 // If there is a refresh pending, bug out early and tell the binder thread to try again
4993 // after the refresh.
4994 if (mRefreshPending) {
4995 ATRACE_NAME("Skipping screenshot for now");
4996 std::unique_lock<std::mutex> captureLock(captureMutex);
4997 captureResult = std::make_optional<status_t>(EAGAIN);
4998 captureCondition.notify_one();
4999 return;
5000 }
5001
5002 status_t result = NO_ERROR;
5003 int fd = -1;
5004 {
5005 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08005006 renderArea.render([&]() {
5007 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5008 useIdentityTransform, forSystem, &fd);
5009 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005010 }
5011
5012 {
5013 std::unique_lock<std::mutex> captureLock(captureMutex);
5014 syncFd = fd;
5015 captureResult = std::make_optional<status_t>(result);
5016 captureCondition.notify_one();
5017 }
5018 });
5019
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005020 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005021 if (result == NO_ERROR) {
5022 captureCondition.wait(captureLock, [&]() { return captureResult; });
5023 while (*captureResult == EAGAIN) {
5024 captureResult.reset();
5025 result = postMessageAsync(message);
5026 if (result != NO_ERROR) {
5027 return result;
5028 }
5029 captureCondition.wait(captureLock, [&]() { return captureResult; });
5030 }
5031 result = *captureResult;
5032 }
5033
5034 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005035 sync_wait(syncFd, -1);
5036 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005037 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005038
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005039 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005040}
5041
chaviwa76b2712017-09-20 12:02:26 -07005042void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
5043 TraverseLayersFunction traverseLayers, bool yswap,
5044 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005045 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005046
Lloyd Pique144e1162017-12-20 16:44:52 -08005047 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005048
5049 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005050 const auto raWidth = renderArea.getWidth();
5051 const auto raHeight = renderArea.getHeight();
5052
5053 const auto reqWidth = renderArea.getReqWidth();
5054 const auto reqHeight = renderArea.getReqHeight();
5055 Rect sourceCrop = renderArea.getSourceCrop();
5056
5057 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5058 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005059
Dan Stozac1879002014-05-22 15:59:05 -07005060 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005061 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005062 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005063 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07005064 }
5065
5066 // ensure that sourceCrop is inside screen
5067 if (sourceCrop.left < 0) {
5068 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5069 }
chaviwa76b2712017-09-20 12:02:26 -07005070 if (sourceCrop.right > raWidth) {
5071 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005072 }
5073 if (sourceCrop.top < 0) {
5074 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5075 }
chaviwa76b2712017-09-20 12:02:26 -07005076 if (sourceCrop.bottom > raHeight) {
5077 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005078 }
5079
Peiyong Lin34beb7a2018-03-28 11:57:12 -07005080 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005081 if (renderArea.getWideColorSupport()) {
5082 outputDataspace = renderArea.getDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08005083 }
Peiyong Linfb069302018-04-25 14:34:31 -07005084 engine.setOutputDataSpace(outputDataspace);
5085 engine.setDisplayMaxLuminance(renderArea.getDisplayMaxLuminance());
Romain Guy88d37dd2017-05-26 17:57:05 -07005086
Mathias Agopian180f10d2013-04-10 22:55:41 -07005087 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005088 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005089
5090 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005091 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
5092 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07005093 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005094
chaviw50da5042018-04-09 13:49:37 -07005095 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005096 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005097 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005098
chaviwa76b2712017-09-20 12:02:26 -07005099 traverseLayers([&](Layer* layer) {
5100 if (filtering) layer->setFiltering(true);
bohu21566132018-03-27 14:36:34 -07005101 layer->draw(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005102 if (filtering) layer->setFiltering(false);
5103 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005104}
5105
chaviwa76b2712017-09-20 12:02:26 -07005106status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5107 TraverseLayersFunction traverseLayers,
5108 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005109 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005110 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005111 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005112 ATRACE_CALL();
5113
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005114 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005115
5116 traverseLayers([&](Layer* layer) {
5117 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5118 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005119
Robert Carr03480e22018-01-04 16:02:06 -08005120 // We allow the system server to take screenshots of secure layers for
5121 // use in situations like the Screen-rotation animation and place
5122 // the impetus on WindowManager to not persist them.
5123 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005124 ALOGW("FB is protected: PERMISSION_DENIED");
5125 return PERMISSION_DENIED;
5126 }
5127
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005128 // this binds the given EGLImage as a framebuffer for the
5129 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005130 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005131 if (bufferBond.getStatus() != NO_ERROR) {
5132 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005133 return INVALID_OPERATION;
5134 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005135
Dan Stozaabcda352017-06-01 14:37:39 -07005136 // this will in fact render into our dequeued buffer
5137 // via an FBO, which means we didn't have to create
5138 // an EGLSurface and therefore we're not
5139 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005140 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005141
Dan Stozaabcda352017-06-01 14:37:39 -07005142 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005143 getRenderEngine().finish();
5144 *outSyncFd = -1;
5145
chaviwa76b2712017-09-20 12:02:26 -07005146 const auto reqWidth = renderArea.getReqWidth();
5147 const auto reqHeight = renderArea.getReqHeight();
5148
Dan Stozaabcda352017-06-01 14:37:39 -07005149 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5150 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005151 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005152 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005153 } else {
5154 base::unique_fd syncFd = getRenderEngine().flush();
5155 if (syncFd < 0) {
5156 getRenderEngine().finish();
5157 }
5158 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005159 }
5160
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005161 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005162}
5163
Mathias Agopiand5556842013-09-19 17:08:37 -07005164void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005165 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005166 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005167 for (size_t y = 0; y < h; y++) {
5168 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5169 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005170 if (p[x] != 0xFF000000) return;
5171 }
5172 }
chaviwa76b2712017-09-20 12:02:26 -07005173 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005174
Robert Carr2047fae2016-11-28 14:09:09 -08005175 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005176 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005177 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005178 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5179 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5180 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5181 static_cast<float>(state.color.a));
5182 i++;
5183 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005184 }
5185}
5186
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005187// ---------------------------------------------------------------------------
5188
Dan Stoza412903f2017-04-27 13:42:17 -07005189void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5190 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005191}
5192
Dan Stoza412903f2017-04-27 13:42:17 -07005193void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5194 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005195}
5196
chaviwa76b2712017-09-20 12:02:26 -07005197void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
5198 int32_t maxLayerZ,
5199 const LayerVector::Visitor& visitor) {
5200 // We loop through the first level of layers without traversing,
5201 // as we need to interpret min/max layer Z in the top level Z space.
5202 for (const auto& layer : mDrawingState.layersSortedByZ) {
5203 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5204 continue;
5205 }
5206 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005207 // relative layers are traversed in Layer::traverseInZOrder
5208 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005209 continue;
5210 }
5211 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005212 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5213 return;
5214 }
chaviwa76b2712017-09-20 12:02:26 -07005215 if (!layer->isVisible()) {
5216 return;
5217 }
5218 visitor(layer);
5219 });
5220 }
5221}
5222
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005223}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005224
Chia-I Wu30505fb2018-03-26 16:20:31 -07005225
Mathias Agopian3f844832013-08-07 21:24:32 -07005226#if defined(__gl_h_)
5227#error "don't include gl/gl.h in this file"
5228#endif
5229
5230#if defined(__gl2_h_)
5231#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005232#endif