blob: 2878b2877b4e65650407db0cb5863748220d7640 [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
Yiwei Zhang243b3782018-05-15 17:40:04 -0700320 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700321 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
322 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
323
Dan Stoza84d619e2018-03-28 17:07:36 -0700324 property_get("debug.sf.early_phase_offset_ns", value, "0");
325 const int earlyWakeupOffsetOffsetNs = atoi(value);
326 ALOGI_IF(earlyWakeupOffsetOffsetNs != 0, "Enabling separate early offset");
327 mVsyncModulator.setPhaseOffsets(sfVsyncPhaseOffsetNs - earlyWakeupOffsetOffsetNs,
328 sfVsyncPhaseOffsetNs);
329
Romain Guy11d63f42017-07-20 12:47:14 -0700330 // We should be reading 'persist.sys.sf.color_saturation' here
331 // but since /data may be encrypted, we need to wait until after vold
332 // comes online to attempt to read the property. The property is
333 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800334
335 if (useTrebleTestingOverride()) {
336 // Without the override SurfaceFlinger cannot connect to HIDL
337 // services that are not listed in the manifests. Considered
338 // deriving the setting from the set service name, but it
339 // would be brittle if the name that's not 'default' is used
340 // for production purposes later on.
341 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
342 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800343}
344
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800345void SurfaceFlinger::onFirstRef()
346{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800347 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800348}
349
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800350SurfaceFlinger::~SurfaceFlinger()
351{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800352}
353
Dan Stozac7014012014-02-14 15:03:43 -0800354void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800355{
356 // the window manager died on us. prepare its eulogy.
357
Andy McFadden13a082e2012-08-24 10:16:42 -0700358 // restore initial conditions (default device unblank, etc)
359 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800360
361 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700362 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800363}
364
Robert Carr1db73f62016-12-21 12:58:51 -0800365static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700366 status_t err = client->initCheck();
367 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800368 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800369 }
Robert Carr1db73f62016-12-21 12:58:51 -0800370 return nullptr;
371}
372
373sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
374 return initClient(new Client(this));
375}
376
377sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
378 const sp<IGraphicBufferProducer>& gbp) {
379 if (authenticateSurfaceTexture(gbp) == false) {
380 return nullptr;
381 }
382 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
383 if (layer == nullptr) {
384 return nullptr;
385 }
386
387 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800388}
389
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700390sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
391 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700392{
393 class DisplayToken : public BBinder {
394 sp<SurfaceFlinger> flinger;
395 virtual ~DisplayToken() {
396 // no more references, this display must be terminated
397 Mutex::Autolock _l(flinger->mStateLock);
398 flinger->mCurrentState.displays.removeItem(this);
399 flinger->setTransactionFlags(eDisplayTransactionNeeded);
400 }
401 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700402 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700403 : flinger(flinger) {
404 }
405 };
406
407 sp<BBinder> token = new DisplayToken(this);
408
409 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700410 DisplayDeviceState info;
411 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700412 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700413 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700414 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800415 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700416 return token;
417}
418
Jesse Hall6c913be2013-08-08 12:15:49 -0700419void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
420 Mutex::Autolock _l(mStateLock);
421
422 ssize_t idx = mCurrentState.displays.indexOfKey(display);
423 if (idx < 0) {
424 ALOGW("destroyDisplay: invalid display token");
425 return;
426 }
427
428 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700429 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700430 ALOGE("destroyDisplay called for non-virtual display");
431 return;
432 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700433 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700434 mCurrentState.displays.removeItemsAt(idx);
435 setTransactionFlags(eDisplayTransactionNeeded);
436}
437
Mathias Agopiane57f2922012-08-09 16:29:12 -0700438sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700439 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700440 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800441 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700442 }
Jesse Hall692c7232012-11-08 15:41:56 -0800443 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700444}
445
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800446void SurfaceFlinger::bootFinished()
447{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700448 if (mStartPropertySetThread->join() != NO_ERROR) {
449 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800450 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800451 const nsecs_t now = systemTime();
452 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000453 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700454
455 // wait patiently for the window manager death
456 const String16 name("window");
457 sp<IBinder> window(defaultServiceManager()->getService(name));
458 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700459 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700460 }
461
Steven Thomas050b2c82017-03-06 11:45:16 -0800462 if (mVrFlinger) {
463 mVrFlinger->OnBootFinished();
464 }
465
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700466 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700467 // formerly we would just kill the process, but we now ask it to exit so it
468 // can choose where to stop the animation.
469 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700470
471 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
472 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
473 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700474
Thierry Strudel2924d012017-08-14 15:19:37 -0700475 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700476 readPersistentProperties();
477 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700478 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800479}
480
Mathias Agopian3f844832013-08-07 21:24:32 -0700481void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700482 class MessageDestroyGLTexture : public MessageBase {
Lloyd Pique144e1162017-12-20 16:44:52 -0800483 RE::RenderEngine& engine;
Mathias Agopian3f844832013-08-07 21:24:32 -0700484 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700485 public:
Lloyd Pique144e1162017-12-20 16:44:52 -0800486 MessageDestroyGLTexture(RE::RenderEngine& engine, uint32_t texture)
487 : engine(engine), texture(texture) {}
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700488 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700489 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700490 return true;
491 }
492 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700493 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700494}
495
Lloyd Piquee83f9312018-02-01 12:53:17 -0800496class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700497public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700498 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000499 const char* name) :
500 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700501 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700502 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000503 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
504 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700505 mDispSync(dispSync),
506 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700507 mVsyncMutex(),
508 mPhaseOffset(phaseOffset),
509 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700510
Lloyd Piquee83f9312018-02-01 12:53:17 -0800511 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700512
Lloyd Piquee83f9312018-02-01 12:53:17 -0800513 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700514 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700515 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000516 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700517 static_cast<DispSync::Callback*>(this));
518 if (err != NO_ERROR) {
519 ALOGE("error registering vsync callback: %s (%d)",
520 strerror(-err), err);
521 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700522 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700523 } else {
524 status_t err = mDispSync->removeEventListener(
525 static_cast<DispSync::Callback*>(this));
526 if (err != NO_ERROR) {
527 ALOGE("error unregistering vsync callback: %s (%d)",
528 strerror(-err), err);
529 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700530 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700531 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700532 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700533 }
534
Lloyd Piquee83f9312018-02-01 12:53:17 -0800535 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700536 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700537 mCallback = callback;
538 }
539
Lloyd Piquee83f9312018-02-01 12:53:17 -0800540 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700541 Mutex::Autolock lock(mVsyncMutex);
542
543 // Normalize phaseOffset to [0, period)
544 auto period = mDispSync->getPeriod();
545 phaseOffset %= period;
546 if (phaseOffset < 0) {
547 // If we're here, then phaseOffset is in (-period, 0). After this
548 // operation, it will be in (0, period)
549 phaseOffset += period;
550 }
551 mPhaseOffset = phaseOffset;
552
553 // If we're not enabled, we don't need to mess with the listeners
554 if (!mEnabled) {
555 return;
556 }
557
Dan Stoza84d619e2018-03-28 17:07:36 -0700558 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
559 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700560 if (err != NO_ERROR) {
Dan Stoza84d619e2018-03-28 17:07:36 -0700561 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700562 strerror(-err), err);
563 }
564 }
565
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700566private:
567 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800568 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700569 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700570 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700571 callback = mCallback;
572
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700573 if (mTraceVsync) {
574 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700575 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700576 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700577 }
578
Peiyong Lin566a3b42018-01-09 18:22:43 -0800579 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700580 callback->onVSyncEvent(when);
581 }
582 }
583
Tim Murray4a4e4a22016-04-19 16:29:23 +0000584 const char* const mName;
585
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700586 int mValue;
587
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700588 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700589 const String8 mVsyncOnLabel;
590 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700591
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700592 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700593
594 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800595 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700596
597 Mutex mVsyncMutex; // Protects the following
598 nsecs_t mPhaseOffset;
599 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700600};
601
Lloyd Piquee83f9312018-02-01 12:53:17 -0800602class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700603public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800604 InjectVSyncSource() = default;
605 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700606
Lloyd Piquee83f9312018-02-01 12:53:17 -0800607 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700608 std::lock_guard<std::mutex> lock(mCallbackMutex);
609 mCallback = callback;
610 }
611
Lloyd Piquee83f9312018-02-01 12:53:17 -0800612 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700613 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700614 if (mCallback) {
615 mCallback->onVSyncEvent(when);
616 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700617 }
618
Lloyd Piquee83f9312018-02-01 12:53:17 -0800619 void setVSyncEnabled(bool) override {}
620 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700621
622private:
623 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800624 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700625};
626
Wei Wangf9b05ee2017-07-19 20:59:39 -0700627// Do not call property_set on main thread which will be blocked by init
628// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700629void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700630 ALOGI( "SurfaceFlinger's main thread ready to run. "
631 "Initializing graphics H/W...");
632
Thierry Strudel2924d012017-08-14 15:19:37 -0700633 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900634
Steven Thomasb02664d2017-07-26 18:48:28 -0700635 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800636
Steven Thomasb02664d2017-07-26 18:48:28 -0700637 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800638 mEventThreadSource =
639 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
640 true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800641 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
642 [this]() { resyncWithRateLimit(); },
643 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800644 "appEventThread");
645 mSfEventThreadSource =
646 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
647 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800648
Lloyd Pique24b0a482018-03-09 18:52:26 -0800649 mSFEventThread =
650 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
651 [this]() { resyncWithRateLimit(); },
652 [this](nsecs_t timestamp) {
653 mInterceptor->saveVSyncEvent(timestamp);
654 },
655 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800656 mEventQueue->setEventThread(mSFEventThread.get());
Dan Stoza84d619e2018-03-28 17:07:36 -0700657 mVsyncModulator.setEventThread(mSFEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800658
Steven Thomasb02664d2017-07-26 18:48:28 -0700659 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800660 getBE().mRenderEngine =
661 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
662 hasWideColorDisplay
663 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
664 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800665 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700666
667 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
668 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800669 getBE().mHwc.reset(
670 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700671 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800672 // Process any initial hotplug and resulting display changes.
673 processDisplayHotplugEventsLocked();
674 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
675 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800676
Lloyd Piquefcd86612017-12-14 17:15:36 -0800677 // make the default display GLContext current so that we can create textures
678 // when creating Layers (which may happens before we render something)
679 getDefaultDisplayDeviceLocked()->makeCurrent();
680
Steven Thomas050b2c82017-03-06 11:45:16 -0800681 if (useVrFlinger) {
682 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700683 // This callback is called from the vr flinger dispatch thread. We
684 // need to call signalTransaction(), which requires holding
685 // mStateLock when we're not on the main thread. Acquiring
686 // mStateLock from the vr flinger dispatch thread might trigger a
687 // deadlock in surface flinger (see b/66916578), so post a message
688 // to be handled on the main thread instead.
689 sp<LambdaMessage> message = new LambdaMessage([=]() {
690 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
691 mVrFlingerRequestsDisplay = requestDisplay;
692 signalTransaction();
693 });
694 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800695 };
David Sodman105b7dc2017-11-04 20:28:14 -0700696 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
697 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800698 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800699 if (!mVrFlinger) {
700 ALOGE("Failed to start vrflinger");
701 }
702 }
703
Lloyd Pique379adc12018-01-22 17:31:47 -0800704 mEventControlThread = std::make_unique<impl::EventControlThread>(
705 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700706
Mathias Agopian92a979a2012-08-02 18:32:23 -0700707 // initialize our drawing state
708 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700709
Andy McFadden13a082e2012-08-24 10:16:42 -0700710 // set initial conditions (e.g. unblank default device)
711 initializeDisplays();
712
David Sodmanbc815282017-11-05 18:57:52 -0800713 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700714
Wei Wangf9b05ee2017-07-19 20:59:39 -0700715 // Inform native graphics APIs whether the present timestamp is supported:
716 if (getHwComposer().hasCapability(
717 HWC2::Capability::PresentFenceIsNotReliable)) {
718 mStartPropertySetThread = new StartPropertySetThread(false);
719 } else {
720 mStartPropertySetThread = new StartPropertySetThread(true);
721 }
722
723 if (mStartPropertySetThread->Start() != NO_ERROR) {
724 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800725 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800726
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800727 mLegacySrgbSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(HWC_DISPLAY_PRIMARY,
728 Dataspace::SRGB_LINEAR);
729
Dan Stoza9e56aa02015-11-02 13:00:03 -0800730 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700731}
732
Romain Guy11d63f42017-07-20 12:47:14 -0700733void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700734 Mutex::Autolock _l(mStateLock);
735
Romain Guy11d63f42017-07-20 12:47:14 -0700736 char value[PROPERTY_VALUE_MAX];
737
738 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800739 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700740 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800741 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100742
743 property_get("persist.sys.sf.native_mode", value, "0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800744 mDisplayColorSetting = toDisplayColorSetting(atoi(value));
745 ALOGV("Display Color Setting is set to %s.",
746 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Romain Guy11d63f42017-07-20 12:47:14 -0700747}
748
Mathias Agopiana67e4182012-06-19 17:26:12 -0700749void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800750 // Start boot animation service by setting a property mailbox
751 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700752 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800753 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700754 if (mStartPropertySetThread->join() != NO_ERROR) {
755 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800756 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700757}
758
Mathias Agopian875d8e12013-06-07 15:35:48 -0700759size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800760 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700761}
762
Mathias Agopian875d8e12013-06-07 15:35:48 -0700763size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800764 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700765}
766
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800767// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800768
Jamie Gennis582270d2011-08-17 18:19:00 -0700769bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800770 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800771 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800772 return authenticateSurfaceTextureLocked(bufferProducer);
773}
774
775bool SurfaceFlinger::authenticateSurfaceTextureLocked(
776 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800777 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800778 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800779}
780
Brian Anderson6b376712017-04-04 10:51:39 -0700781status_t SurfaceFlinger::getSupportedFrameTimestamps(
782 std::vector<FrameEvent>* outSupported) const {
783 *outSupported = {
784 FrameEvent::REQUESTED_PRESENT,
785 FrameEvent::ACQUIRE,
786 FrameEvent::LATCH,
787 FrameEvent::FIRST_REFRESH_START,
788 FrameEvent::LAST_REFRESH_START,
789 FrameEvent::GPU_COMPOSITION_DONE,
790 FrameEvent::DEQUEUE_READY,
791 FrameEvent::RELEASE,
792 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700793 ConditionalLock _l(mStateLock,
794 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700795 if (!getHwComposer().hasCapability(
796 HWC2::Capability::PresentFenceIsNotReliable)) {
797 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
798 }
799 return NO_ERROR;
800}
801
Dan Stoza7f7da322014-05-02 15:26:25 -0700802status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
803 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800804 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700805 return BAD_VALUE;
806 }
807
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500808 if (!display.get())
809 return NAME_NOT_FOUND;
810
Jesse Hall692c7232012-11-08 15:41:56 -0800811 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700812 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800813 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700814 type = i;
815 break;
816 }
817 }
818
819 if (type < 0) {
820 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700821 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700822
Mathias Agopian8b736f12012-08-13 17:54:26 -0700823 // TODO: Not sure if display density should handled by SF any longer
824 class Density {
825 static int getDensityFromProperty(char const* propName) {
826 char property[PROPERTY_VALUE_MAX];
827 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800828 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700829 density = atoi(property);
830 }
831 return density;
832 }
833 public:
834 static int getEmuDensity() {
835 return getDensityFromProperty("qemu.sf.lcd_density"); }
836 static int getBuildDensity() {
837 return getDensityFromProperty("ro.sf.lcd_density"); }
838 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700839
Dan Stoza7f7da322014-05-02 15:26:25 -0700840 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700841
Steven Thomas6d8110b2017-08-31 18:24:21 -0700842 ConditionalLock _l(mStateLock,
843 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800844 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700845 DisplayInfo info = DisplayInfo();
846
Dan Stoza9e56aa02015-11-02 13:00:03 -0800847 float xdpi = hwConfig->getDpiX();
848 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700849
850 if (type == DisplayDevice::DISPLAY_PRIMARY) {
851 // The density of the device is provided by a build property
852 float density = Density::getBuildDensity() / 160.0f;
853 if (density == 0) {
854 // the build doesn't provide a density -- this is wrong!
855 // use xdpi instead
856 ALOGE("ro.sf.lcd_density must be defined as a build property");
857 density = xdpi / 160.0f;
858 }
859 if (Density::getEmuDensity()) {
860 // if "qemu.sf.lcd_density" is specified, it overrides everything
861 xdpi = ydpi = density = Density::getEmuDensity();
862 density /= 160.0f;
863 }
864 info.density = density;
865
866 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700867 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800868 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700869 } else {
870 // TODO: where should this value come from?
871 static const int TV_DENSITY = 213;
872 info.density = TV_DENSITY / 160.0f;
873 info.orientation = 0;
874 }
875
Dan Stoza9e56aa02015-11-02 13:00:03 -0800876 info.w = hwConfig->getWidth();
877 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700878 info.xdpi = xdpi;
879 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800880 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900881 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800882
Andy McFadden91b2ca82014-06-13 14:04:23 -0700883 // This is how far in advance a buffer must be queued for
884 // presentation at a given time. If you want a buffer to appear
885 // on the screen at time N, you must submit the buffer before
886 // (N - presentationDeadline).
887 //
888 // Normally it's one full refresh period (to give SF a chance to
889 // latch the buffer), but this can be reduced by configuring a
890 // DispSync offset. Any additional delays introduced by the hardware
891 // composer or panel must be accounted for here.
892 //
893 // We add an additional 1ms to allow for processing time and
894 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800895 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800896 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700897
898 // All non-virtual displays are currently considered secure.
899 info.secure = true;
900
Michael Wright28f24d02016-07-12 13:30:53 -0700901 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700902 }
903
Dan Stoza7f7da322014-05-02 15:26:25 -0700904 return NO_ERROR;
905}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700906
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800907status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700908 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800909 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700910 return BAD_VALUE;
911 }
912
913 // FIXME for now we always return stats for the primary display
914 memset(stats, 0, sizeof(*stats));
915 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
916 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
917 return NO_ERROR;
918}
919
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700920int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800921 if (display == nullptr) {
922 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800923 return BAD_VALUE;
924 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700925
926 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800927 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700928 return device->getActiveConfig();
929 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700930
Dan Stoza24a42e92015-03-09 10:04:11 -0700931 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700932}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700933
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700934void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
935 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
936 this);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700937 int currentMode = hw->getActiveConfig();
938
939 if (mode == currentMode) {
940 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
941 return;
942 }
943
Dominik Laskowski281644e2018-04-19 15:47:35 -0700944 if (hw->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700945 ALOGW("Trying to set config for virtual display");
946 return;
947 }
948
949 hw->setActiveConfig(mode);
Dominik Laskowski281644e2018-04-19 15:47:35 -0700950 getHwComposer().setActiveConfig(hw->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700951}
952
953status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
954 class MessageSetActiveConfig: public MessageBase {
955 SurfaceFlinger& mFlinger;
956 sp<IBinder> mDisplay;
957 int mMode;
958 public:
959 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
960 int mode) :
961 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
962 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700963 Vector<DisplayInfo> configs;
964 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700965 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700966 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700967 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700968 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700969 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700970 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800971 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700972 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700973 mMode, mDisplay.get());
Dominik Laskowski281644e2018-04-19 15:47:35 -0700974 } else if (hw->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700975 ALOGW("Attempt to set active config = %d for virtual display",
976 mMode);
977 } else {
978 mFlinger.setActiveConfigInternal(hw, mMode);
979 }
980 return true;
981 }
982 };
983 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
984 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700985 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700986}
Michael Wright28f24d02016-07-12 13:30:53 -0700987status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -0700988 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700989 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
990 return BAD_VALUE;
991 }
992
993 if (!display.get()) {
994 return NAME_NOT_FOUND;
995 }
996
997 int32_t type = NAME_NOT_FOUND;
998 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
999 if (display == mBuiltinDisplays[i]) {
1000 type = i;
1001 break;
1002 }
1003 }
1004
1005 if (type < 0) {
1006 return type;
1007 }
1008
Peiyong Lina52f0292018-03-14 17:26:31 -07001009 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001010 {
1011 ConditionalLock _l(mStateLock,
1012 std::this_thread::get_id() != mMainThreadId);
1013 modes = getHwComposer().getColorModes(type);
1014 }
Michael Wright28f24d02016-07-12 13:30:53 -07001015 outColorModes->clear();
1016 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1017
1018 return NO_ERROR;
1019}
1020
Peiyong Lina52f0292018-03-14 17:26:31 -07001021ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001022 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -07001023 if (device != nullptr) {
1024 return device->getActiveColorMode();
1025 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001026 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001027}
1028
1029void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001030 ColorMode mode, Dataspace dataSpace,
1031 RenderIntent renderIntent) {
Peiyong Lina52f0292018-03-14 17:26:31 -07001032 ColorMode currentMode = hw->getActiveColorMode();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001033 Dataspace currentDataSpace = hw->getCompositionDataSpace();
Peiyong Lin38e9a562018-04-10 16:24:20 -07001034 RenderIntent currentRenderIntent = hw->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001035
Peiyong Lin38e9a562018-04-10 16:24:20 -07001036 if (mode == currentMode && dataSpace == currentDataSpace &&
1037 renderIntent == currentRenderIntent) {
1038 return;
1039 }
1040
Dominik Laskowski281644e2018-04-19 15:47:35 -07001041 if (hw->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001042 ALOGW("Trying to set config for virtual display");
1043 return;
1044 }
1045
1046 hw->setActiveColorMode(mode);
1047 hw->setCompositionDataSpace(dataSpace);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001048 hw->setActiveRenderIntent(renderIntent);
Dominik Laskowski281644e2018-04-19 15:47:35 -07001049 getHwComposer().setActiveColorMode(hw->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001050
1051 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
1052 decodeColorMode(mode).c_str(), mode,
1053 decodeRenderIntent(renderIntent).c_str(), renderIntent,
1054 hw->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001055}
1056
1057
1058status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001059 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -07001060 class MessageSetActiveColorMode: public MessageBase {
1061 SurfaceFlinger& mFlinger;
1062 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -07001063 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001064 public:
1065 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -07001066 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -07001067 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1068 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -07001069 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001070 mFlinger.getDisplayColorModes(mDisplay, &modes);
1071 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -07001072 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001073 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1074 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001075 return true;
1076 }
1077 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1078 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001079 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1080 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Dominik Laskowski281644e2018-04-19 15:47:35 -07001081 } else if (hw->isVirtual()) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001082 ALOGW("Attempt to set active color mode %s %d for virtual display",
1083 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001084 } else {
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001085 mFlinger.setActiveColorModeInternal(hw, mMode, Dataspace::UNKNOWN,
1086 RenderIntent::COLORIMETRIC);
Michael Wright28f24d02016-07-12 13:30:53 -07001087 }
1088 return true;
1089 }
1090 };
1091 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1092 postMessageSync(msg);
1093 return NO_ERROR;
1094}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001095
Svetoslavd85084b2014-03-20 10:28:31 -07001096status_t SurfaceFlinger::clearAnimationFrameStats() {
1097 Mutex::Autolock _l(mStateLock);
1098 mAnimFrameTracker.clearStats();
1099 return NO_ERROR;
1100}
1101
1102status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1103 Mutex::Autolock _l(mStateLock);
1104 mAnimFrameTracker.getStats(outStats);
1105 return NO_ERROR;
1106}
1107
Dan Stozac4f471e2016-03-24 09:31:08 -07001108status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1109 HdrCapabilities* outCapabilities) const {
1110 Mutex::Autolock _l(mStateLock);
1111
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001112 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001113 if (displayDevice == nullptr) {
1114 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1115 return BAD_VALUE;
1116 }
1117
Peiyong Linfb069302018-04-25 14:34:31 -07001118 // At this point the DisplayDeivce should already be set up,
1119 // meaning the luminance information is already queried from
1120 // hardware composer and stored properly.
1121 const HdrCapabilities& capabilities = displayDevice->getHdrCapabilities();
1122 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1123 capabilities.getDesiredMaxLuminance(),
1124 capabilities.getDesiredMaxAverageLuminance(),
1125 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001126
1127 return NO_ERROR;
1128}
1129
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001130status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001131 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1132 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001133
Chia-I Wu90f669f2017-10-05 14:24:41 -07001134 if (mInjectVSyncs == enable) {
1135 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001136 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001137
1138 if (enable) {
1139 ALOGV("VSync Injections enabled");
1140 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001141 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001142 mInjectorEventThread = std::make_unique<
1143 impl::EventThread>(mVSyncInjector.get(),
1144 [this]() { resyncWithRateLimit(); },
1145 impl::EventThread::InterceptVSyncsCallback(),
1146 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001147 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001148 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001149 } else {
1150 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001151 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001152 }
1153
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001154 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001155 });
1156 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001157 return NO_ERROR;
1158}
1159
1160status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001161 Mutex::Autolock _l(mStateLock);
1162
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001163 if (!mInjectVSyncs) {
1164 ALOGE("VSync Injections not enabled");
1165 return BAD_VALUE;
1166 }
1167 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1168 ALOGV("Injecting VSync inside SurfaceFlinger");
1169 mVSyncInjector->onInjectSyncEvent(when);
1170 }
1171 return NO_ERROR;
1172}
1173
Lloyd Pique755e3192018-01-31 16:46:15 -08001174status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1175 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001176 IPCThreadState* ipc = IPCThreadState::self();
1177 const int pid = ipc->getCallingPid();
1178 const int uid = ipc->getCallingUid();
1179 if ((uid != AID_SHELL) &&
1180 !PermissionCache::checkPermission(sDump, pid, uid)) {
1181 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1182 return PERMISSION_DENIED;
1183 }
1184
1185 // Try to acquire a lock for 1s, fail gracefully
1186 const status_t err = mStateLock.timedLock(s2ns(1));
1187 const bool locked = (err == NO_ERROR);
1188 if (!locked) {
1189 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1190 return TIMED_OUT;
1191 }
1192
1193 outLayers->clear();
1194 mCurrentState.traverseInZOrder([&](Layer* layer) {
1195 outLayers->push_back(layer->getLayerDebugInfo());
1196 });
1197
1198 mStateLock.unlock();
1199 return NO_ERROR;
1200}
1201
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001202// ----------------------------------------------------------------------------
1203
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001204sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1205 ISurfaceComposer::VsyncSource vsyncSource) {
1206 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1207 return mSFEventThread->createEventConnection();
1208 } else {
1209 return mEventThread->createEventConnection();
1210 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001211}
1212
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001213// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001214
1215void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001216 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001217}
1218
1219void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001220 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001221}
1222
1223void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001224 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001225}
1226
1227void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001228 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001229 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001230}
1231
1232status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001233 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001234 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001235}
1236
1237status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001238 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001239 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001240 if (res == NO_ERROR) {
1241 msg->wait();
1242 }
1243 return res;
1244}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001245
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001246void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001247 do {
1248 waitForEvent();
1249 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001250}
1251
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001252void SurfaceFlinger::enableHardwareVsync() {
1253 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001254 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001255 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001256 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1257 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001258 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001259 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001260}
1261
Jesse Hall948fe0c2013-10-14 12:56:09 -07001262void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001263 Mutex::Autolock _l(mHWVsyncLock);
1264
Jesse Hall948fe0c2013-10-14 12:56:09 -07001265 if (makeAvailable) {
1266 mHWVsyncAvailable = true;
1267 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001268 // Hardware vsync is not currently available, so abort the resync
1269 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001270 return;
1271 }
1272
David Sodman105b7dc2017-11-04 20:28:14 -07001273 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001274 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001275
1276 mPrimaryDispSync.reset();
1277 mPrimaryDispSync.setPeriod(period);
1278
1279 if (!mPrimaryHWVsyncEnabled) {
1280 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001281 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1282 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001283 mPrimaryHWVsyncEnabled = true;
1284 }
1285}
1286
Jesse Hall948fe0c2013-10-14 12:56:09 -07001287void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001288 Mutex::Autolock _l(mHWVsyncLock);
1289 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001290 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1291 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001292 mPrimaryDispSync.endResync();
1293 mPrimaryHWVsyncEnabled = false;
1294 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001295 if (makeUnavailable) {
1296 mHWVsyncAvailable = false;
1297 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001298}
1299
Tim Murray4a4e4a22016-04-19 16:29:23 +00001300void SurfaceFlinger::resyncWithRateLimit() {
1301 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001302
1303 // No explicit locking is needed here since EventThread holds a lock while calling this method
1304 static nsecs_t sLastResyncAttempted = 0;
1305 const nsecs_t now = systemTime();
1306 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001307 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001308 }
Dan Stoza57164302017-05-08 14:03:54 -07001309 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001310}
1311
Steven Thomasb02664d2017-07-26 18:48:28 -07001312void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1313 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001314 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001315 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001316 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001317 return;
1318 }
1319
1320 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001321 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001322 return;
1323 }
1324
Jamie Gennisd1700752013-10-14 12:22:52 -07001325 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001326
Jamie Gennisd1700752013-10-14 12:22:52 -07001327 { // Scope for the lock
1328 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001329 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001330 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001331 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001332 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001333
1334 if (needsHwVsync) {
1335 enableHardwareVsync();
1336 } else {
1337 disableHardwareVsync(false);
1338 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001339}
1340
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001341void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001342 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1343 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001344}
1345
Lloyd Pique715a2c12017-12-14 17:18:08 -08001346void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1347 HWC2::Connection connection) {
1348 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1349 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001350
Lloyd Piqueba04e622017-12-14 17:11:26 -08001351 // Ignore events that do not have the right sequenceId.
1352 if (sequenceId != getBE().mComposerSequenceId) {
1353 return;
1354 }
1355
Steven Thomasb02664d2017-07-26 18:48:28 -07001356 // Only lock if we're not on the main thread. This function is normally
1357 // called on a hwbinder thread, but for the primary display it's called on
1358 // the main thread with the state lock already held, so don't attempt to
1359 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001360 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001361
Lloyd Pique715a2c12017-12-14 17:18:08 -08001362 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001363
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001364 if (std::this_thread::get_id() == mMainThreadId) {
1365 // Process all pending hot plug events immediately if we are on the main thread.
1366 processDisplayHotplugEventsLocked();
1367 }
1368
Lloyd Piqueba04e622017-12-14 17:11:26 -08001369 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001370}
1371
Steven Thomasb02664d2017-07-26 18:48:28 -07001372void SurfaceFlinger::onRefreshReceived(int sequenceId,
1373 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001374 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001375 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001376 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001377 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001378 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001379}
1380
Dan Stoza9e56aa02015-11-02 13:00:03 -08001381void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001382 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001383 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001384 getHwComposer().setVsyncEnabled(disp,
1385 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001386}
1387
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001388// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001389void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001390 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001391 // Clear the drawing state so that the logic inside of
1392 // handleTransactionLocked will fire. It will determine the delta between
1393 // mCurrentState and mDrawingState and re-apply all changes when we make the
1394 // transition.
1395 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001396 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001397 mDisplays.clear();
1398}
1399
Steven Thomas050b2c82017-03-06 11:45:16 -08001400void SurfaceFlinger::updateVrFlinger() {
1401 if (!mVrFlinger)
1402 return;
1403 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001404 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001405 return;
1406 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001407
David Sodman105b7dc2017-11-04 20:28:14 -07001408 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001409 ALOGE("Vr flinger is only supported for remote hardware composer"
1410 " service connections. Ignoring request to transition to vr"
1411 " flinger.");
1412 mVrFlingerRequestsDisplay = false;
1413 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001414 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001415
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001416 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001417
Steven Thomasb02664d2017-07-26 18:48:28 -07001418 int currentDisplayPowerMode = getDisplayDeviceLocked(
1419 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001420
Steven Thomasb02664d2017-07-26 18:48:28 -07001421 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001422 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001423 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001424
Steven Thomasb02664d2017-07-26 18:48:28 -07001425 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001426 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001427 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1428 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001429 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001430
David Sodman105b7dc2017-11-04 20:28:14 -07001431 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1432 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001433
1434 if (vrFlingerRequestsDisplay) {
1435 mVrFlinger->GrantDisplayOwnership();
1436 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001437 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001438 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001439
1440 mVisibleRegionsDirty = true;
1441 invalidateHwcGeometry();
1442
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001443 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001444 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1445 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1446 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001447
Steven Thomasb02664d2017-07-26 18:48:28 -07001448 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001449 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001450 const nsecs_t period = activeConfig->getVsyncPeriod();
1451 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001452
Steven Thomasb02664d2017-07-26 18:48:28 -07001453 // Use phase of 0 since phase is not known.
1454 // Use latency of 0, which will snap to the ideal latency.
1455 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001456
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001457 android_atomic_or(1, &mRepaintEverything);
1458 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001459}
1460
Mathias Agopian4fec8732012-06-29 14:12:52 -07001461void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001462 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001463 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001464 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001465 bool frameMissed = !mHadClientComposition &&
1466 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001467 (mPreviousPresentFence->getSignalTime() ==
1468 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001469 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001470 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001471 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001472 mTimeStats.incrementMissedFrames();
1473 if (mPropagateBackpressure) {
1474 signalLayerUpdate();
1475 break;
1476 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001477 }
Dan Stoza50182882016-07-08 12:02:20 -07001478
Steven Thomas050b2c82017-03-06 11:45:16 -08001479 // Now that we're going to make it to the handleMessageTransaction()
1480 // call below it's safe to call updateVrFlinger(), which will
1481 // potentially trigger a display handoff.
1482 updateVrFlinger();
1483
Dan Stoza6b9454d2014-11-07 16:00:59 -08001484 bool refreshNeeded = handleMessageTransaction();
1485 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001486 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001487 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001488 // Signal a refresh if a transaction modified the window state,
1489 // a new buffer was latched, or if HWC has requested a full
1490 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001491 signalRefresh();
1492 }
1493 break;
1494 }
1495 case MessageQueue::REFRESH: {
1496 handleMessageRefresh();
1497 break;
1498 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001499 }
1500}
1501
Dan Stoza6b9454d2014-11-07 16:00:59 -08001502bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001503 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001504 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001505 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001506 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001507 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001508 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001509}
1510
Dan Stoza6b9454d2014-11-07 16:00:59 -08001511bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001512 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001513 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001514}
1515
1516void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001517 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001518
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001519 mRefreshPending = false;
1520
Chia-I Wu30505fb2018-03-26 16:20:31 -07001521 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001522
Chia-I Wu30505fb2018-03-26 16:20:31 -07001523 preComposition(refreshStartTime);
1524 rebuildLayerStacks();
1525 setUpHWComposer();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001526 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001527 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001528 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001529 doComposition();
Chia-I Wu30505fb2018-03-26 16:20:31 -07001530 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001531
David Sodman105b7dc2017-11-04 20:28:14 -07001532 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001533
1534 mHadClientComposition = false;
1535 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1536 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1537 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001538 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001539 }
Dan Stoza84d619e2018-03-28 17:07:36 -07001540 mVsyncModulator.setLastFrameUsedRenderEngine(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001541
Dan Stoza9e56aa02015-11-02 13:00:03 -08001542 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001543}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001544
Mathias Agopiancd60f992012-08-16 16:28:27 -07001545void SurfaceFlinger::doDebugFlashRegions()
1546{
1547 // is debugging enabled
1548 if (CC_LIKELY(!mDebugRegion))
1549 return;
1550
1551 const bool repaintEverything = mRepaintEverything;
1552 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1553 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001554 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001555 // transform the dirty region into this screen's coordinate space
1556 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1557 if (!dirtyRegion.isEmpty()) {
1558 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001559 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001560
1561 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001562 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001563 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001564 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1565
Mathias Agopianda27af92012-09-13 18:17:13 -07001566 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001567 }
1568 }
1569 }
1570
1571 postFramebuffer();
1572
1573 if (mDebugRegion > 1) {
1574 usleep(mDebugRegion * 1000);
1575 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001576
Dan Stoza9e56aa02015-11-02 13:00:03 -08001577 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001578 auto& displayDevice = mDisplays[displayId];
1579 if (!displayDevice->isDisplayOn()) {
1580 continue;
1581 }
1582
David Sodman105b7dc2017-11-04 20:28:14 -07001583 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1584 ALOGE_IF(result != NO_ERROR,
1585 "prepareFrame for display %zd failed:"
1586 " %d (%s)",
1587 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001588 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001589}
1590
Adrian Roos1e1a1282017-11-01 19:05:31 +01001591void SurfaceFlinger::doTracing(const char* where) {
1592 ATRACE_CALL();
1593 ATRACE_NAME(where);
1594 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001595 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001596 }
1597}
1598
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001599void SurfaceFlinger::logLayerStats() {
1600 ATRACE_CALL();
1601 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1602 int32_t hwcId = -1;
1603 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1604 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1605 if (displayDevice->isPrimary()) {
1606 hwcId = displayDevice->getHwcDisplayId();
1607 break;
1608 }
1609 }
1610 if (hwcId < 0) {
1611 ALOGE("LayerStats: Hmmm, no primary display?");
1612 return;
1613 }
1614 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1615 }
1616}
1617
Chia-I Wu30505fb2018-03-26 16:20:31 -07001618void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001619{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001620 ATRACE_CALL();
1621 ALOGV("preComposition");
1622
Mathias Agopiancd60f992012-08-16 16:28:27 -07001623 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001624 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001625 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001626 needExtraInvalidate = true;
1627 }
Robert Carr2047fae2016-11-28 14:09:09 -08001628 });
1629
Mathias Agopiancd60f992012-08-16 16:28:27 -07001630 if (needExtraInvalidate) {
1631 signalLayerUpdate();
1632 }
1633}
1634
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001635void SurfaceFlinger::updateCompositorTiming(
1636 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1637 std::shared_ptr<FenceTime>& presentFenceTime) {
1638 // Update queue of past composite+present times and determine the
1639 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001640 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001641 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001642 while (!getBE().mCompositePresentTimes.empty()) {
1643 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001644 // Cached values should have been updated before calling this method,
1645 // which helps avoid duplicate syscalls.
1646 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1647 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1648 break;
1649 }
1650 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001651 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001652 }
1653
1654 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001655 while (getBE().mCompositePresentTimes.size() > 16) {
1656 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001657 }
1658
Brian Andersond0010582017-03-07 13:20:31 -08001659 setCompositorTimingSnapped(
1660 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1661}
1662
1663void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1664 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001665 // Integer division and modulo round toward 0 not -inf, so we need to
1666 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001667 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001668 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1669 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1670
Brian Andersond0010582017-03-07 13:20:31 -08001671 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1672 if (idealLatency <= 0) {
1673 idealLatency = vsyncInterval;
1674 }
1675
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001676 // Snap the latency to a value that removes scheduling jitter from the
1677 // composition and present times, which often have >1ms of jitter.
1678 // Reducing jitter is important if an app attempts to extrapolate
1679 // something (such as user input) to an accurate diasplay time.
1680 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1681 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001682 nsecs_t bias = vsyncInterval / 2;
1683 int64_t extraVsyncs =
1684 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1685 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1686 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001687
David Sodman99974d22017-11-28 12:04:33 -08001688 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1689 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1690 getBE().mCompositorTiming.interval = vsyncInterval;
1691 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001692}
1693
Chia-I Wu30505fb2018-03-26 16:20:31 -07001694void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001695{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001696 ATRACE_CALL();
1697 ALOGV("postComposition");
1698
Brian Anderson3546a3f2016-07-14 11:51:14 -07001699 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001700 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001701 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001702 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001703 }
1704
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001705 // |mStateLock| not needed as we are on the main thread
1706 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001707
David Sodman73beded2017-11-15 11:56:06 -08001708 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001709 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001710 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001711 glCompositionDoneFenceTime =
1712 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001713 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001714 } else {
1715 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1716 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001717
David Sodman73beded2017-11-15 11:56:06 -08001718 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001719 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001720 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001721 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001722
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001723 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1724 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1725
Chia-I Wu30505fb2018-03-26 16:20:31 -07001726 // We use the refreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001727 // when we started doing work for this frame, but that should be okay
1728 // since updateCompositorTiming has snapping logic.
1729 updateCompositorTiming(
Chia-I Wu30505fb2018-03-26 16:20:31 -07001730 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001731 CompositorTiming compositorTiming;
1732 {
David Sodman99974d22017-11-28 12:04:33 -08001733 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1734 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001735 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001736
Robert Carr2047fae2016-11-28 14:09:09 -08001737 mDrawingState.traverseInZOrder([&](Layer* layer) {
1738 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001739 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001740 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001741 recordBufferingStats(layer->getName().string(),
1742 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001743 }
Robert Carr2047fae2016-11-28 14:09:09 -08001744 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001745
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001746 if (presentFenceTime->isValid()) {
1747 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001748 enableHardwareVsync();
1749 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001750 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001751 }
1752 }
1753
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001754 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001755 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001756 enableHardwareVsync();
1757 }
1758 }
1759
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001760 if (mAnimCompositionPending) {
1761 mAnimCompositionPending = false;
1762
Brian Anderson4e606e32017-03-16 15:34:57 -07001763 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001764 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001765 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001766 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001767 // The HWC doesn't support present fences, so use the refresh
1768 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001769 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001770 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001771 mAnimFrameTracker.setActualPresentTime(presentTime);
1772 }
1773 mAnimFrameTracker.advanceFrame();
1774 }
Dan Stozab90cf072015-03-05 11:05:59 -08001775
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001776 mTimeStats.incrementTotalFrames();
1777 if (mHadClientComposition) {
1778 mTimeStats.incrementClientCompositionFrames();
1779 }
1780
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001781 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1782 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001783 return;
1784 }
1785
1786 nsecs_t currentTime = systemTime();
1787 if (mHasPoweredOff) {
1788 mHasPoweredOff = false;
1789 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001790 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001791 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001792 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1793 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001794 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001795 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001796 }
David Sodman4a36e932017-11-07 14:29:47 -08001797 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001798 }
David Sodman4a36e932017-11-07 14:29:47 -08001799 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001800}
1801
1802void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001803 ATRACE_CALL();
1804 ALOGV("rebuildLayerStacks");
1805
Mathias Agopiancd60f992012-08-16 16:28:27 -07001806 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001807 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001808 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001809 mVisibleRegionsDirty = false;
1810 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001811
Jeff Sharkey76488112017-02-27 14:15:18 -07001812 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1813 Region opaqueRegion;
1814 Region dirtyRegion;
1815 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001816 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001817 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1818 const Transform& tr(displayDevice->getTransform());
1819 const Rect bounds(displayDevice->getBounds());
1820 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001821 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001822
Jeff Sharkey76488112017-02-27 14:15:18 -07001823 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001824 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001825 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1826 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001827 Region drawRegion(tr.transform(
1828 layer->visibleNonTransparentRegion));
1829 drawRegion.andSelf(bounds);
1830 if (!drawRegion.isEmpty()) {
1831 layersSortedByZ.add(layer);
1832 } else {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001833 // Clear out the HWC layer if this layer was
1834 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001835 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001836 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001837 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001838 } else {
1839 // WM changes displayDevice->layerStack upon sleep/awake.
1840 // Here we make sure we delete the HWC layers even if
1841 // WM changed their layer stack.
1842 hwcLayerDestroyed = layer->destroyHwcLayer(
1843 displayDevice->getHwcDisplayId());
Chia-I Wu83806892017-11-16 10:50:20 -08001844 }
1845
1846 // If a layer is not going to get a release fence because
1847 // it is invisible, but it is also going to release its
1848 // old buffer, add it to the list of layers needing
1849 // fences.
1850 if (hwcLayerDestroyed) {
1851 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1852 mLayersWithQueuedFrames.cend(), layer);
1853 if (found != mLayersWithQueuedFrames.cend()) {
1854 layersNeedingFences.add(layer);
1855 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001856 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001857 });
1858 }
1859 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001860 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001861 displayDevice->undefinedRegion.set(bounds);
1862 displayDevice->undefinedRegion.subtractSelf(
1863 tr.transform(opaqueRegion));
1864 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001865 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001866 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001867}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001868
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001869// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001870// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001871// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001872// - Dataspace::DISPLAY_P3
1873// - Dataspace::V0_SCRGB_LINEAR
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001874// The returned HDR data space is one of
1875// - Dataspace::UNKNOWN
1876// - Dataspace::BT2020_HLG
1877// - Dataspace::BT2020_PQ
1878Dataspace SurfaceFlinger::getBestDataspace(
1879 const sp<const DisplayDevice>& displayDevice, Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001880 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001881 *outHdrDataSpace = Dataspace::UNKNOWN;
1882
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001883 for (const auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001884 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001885 case Dataspace::V0_SCRGB:
1886 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001887 bestDataSpace = Dataspace::V0_SCRGB_LINEAR;
Peiyong Linf59a7192018-04-25 11:19:31 -07001888 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001889 case Dataspace::DISPLAY_P3:
Chia-I Wu7112a112018-05-07 15:27:06 -07001890 if (bestDataSpace == Dataspace::SRGB) {
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001891 bestDataSpace = Dataspace::DISPLAY_P3;
1892 }
1893 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001894 case Dataspace::BT2020_PQ:
1895 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001896 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001897 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001898 case Dataspace::BT2020_HLG:
1899 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001900 // When there's mixed PQ content and HLG content, we set the HDR
1901 // data space to be BT2020_PQ and convert HLG to PQ.
1902 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1903 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001904 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001905 break;
1906 default:
1907 break;
1908 }
Romain Guy54f154a2017-10-24 21:40:32 +01001909 }
1910
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001911 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001912}
1913
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001914// Pick the ColorMode / Dataspace for the display device.
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001915void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& displayDevice,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001916 ColorMode* outMode, Dataspace* outDataSpace,
1917 RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001918 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1919 *outMode = ColorMode::NATIVE;
1920 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001921 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001922 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001923 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001924
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001925 Dataspace hdrDataSpace;
1926 Dataspace bestDataSpace = getBestDataspace(displayDevice, &hdrDataSpace);
1927
1928 if (hdrDataSpace == Dataspace::BT2020_PQ) {
1929 // Hardware composer can handle BT2100 ColorMode only when
1930 // - colorimetrical tone mapping is supported, or
1931 // - Auto mode is turned on and enhanced tone mapping is supported.
1932 if (displayDevice->hasBT2100PQColorimetricSupport() ||
1933 (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
1934 displayDevice->hasBT2100PQEnhanceSupport())) {
1935 *outMode = ColorMode::BT2100_PQ;
1936 *outDataSpace = Dataspace::BT2020_PQ;
1937 } else if (displayDevice->hasHDR10Support()) {
1938 // Legacy HDR support. HDR layers are treated as UNKNOWN layers.
1939 hdrDataSpace = Dataspace::UNKNOWN;
1940 } else {
1941 // Simulate PQ through RenderEngine, pick DISPLAY_P3 color mode.
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001942 *outMode = ColorMode::DISPLAY_P3;
1943 *outDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001944 }
1945 } else if (hdrDataSpace == Dataspace::BT2020_HLG) {
1946 if (displayDevice->hasBT2100HLGColorimetricSupport() ||
1947 (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
1948 displayDevice->hasBT2100HLGEnhanceSupport())) {
1949 *outMode = ColorMode::BT2100_HLG;
1950 *outDataSpace = Dataspace::BT2020_HLG;
1951 } else if (displayDevice->hasHLGSupport()) {
1952 // Legacy HDR support. HDR layers are treated as UNKNOWN layers.
1953 hdrDataSpace = Dataspace::UNKNOWN;
1954 } else {
1955 // Simulate HLG through RenderEngine, pick DISPLAY_P3 color mode.
1956 *outMode = ColorMode::DISPLAY_P3;
1957 *outDataSpace = Dataspace::DISPLAY_P3;
1958 }
1959 }
1960
1961 // At this point, there's no HDR layer.
1962 if (hdrDataSpace == Dataspace::UNKNOWN) {
1963 switch (bestDataSpace) {
1964 case Dataspace::DISPLAY_P3:
1965 case Dataspace::V0_SCRGB_LINEAR:
1966 *outMode = ColorMode::DISPLAY_P3;
1967 *outDataSpace = Dataspace::DISPLAY_P3;
1968 break;
1969 default:
1970 *outMode = ColorMode::SRGB;
Chia-I Wu7112a112018-05-07 15:27:06 -07001971 *outDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001972 break;
1973 }
1974 }
1975 *outRenderIntent = pickRenderIntent(displayDevice, *outMode);
1976}
1977
1978RenderIntent SurfaceFlinger::pickRenderIntent(const sp<DisplayDevice>& displayDevice,
1979 ColorMode colorMode) const {
1980 // Native Mode means the display is not color managed, and whichever
1981 // render intent is picked doesn't matter, thus return
1982 // RenderIntent::COLORIMETRIC as default here.
1983 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1984 return RenderIntent::COLORIMETRIC;
1985 }
1986
1987 // In Auto Color Mode, we want to strech to panel color space, right now
1988 // only the built-in display supports it.
1989 if (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
1990 mBuiltinDisplaySupportsEnhance && displayDevice->isPrimary()) {
1991 switch (colorMode) {
1992 case ColorMode::DISPLAY_P3:
1993 case ColorMode::SRGB:
1994 return RenderIntent::ENHANCE;
1995 // In Auto Color Mode, BT2100_PQ and BT2100_HLG will only be picked
1996 // when TONE_MAP_ENHANCE or TONE_MAP_COLORIMETRIC is supported.
1997 // If TONE_MAP_ENHANCE is not supported, fall back to TONE_MAP_COLORIMETRIC.
1998 case ColorMode::BT2100_PQ:
1999 return displayDevice->hasBT2100PQEnhanceSupport() ?
2000 RenderIntent::TONE_MAP_ENHANCE : RenderIntent::TONE_MAP_COLORIMETRIC;
2001 case ColorMode::BT2100_HLG:
2002 return displayDevice->hasBT2100HLGEnhanceSupport() ?
2003 RenderIntent::TONE_MAP_ENHANCE : RenderIntent::TONE_MAP_COLORIMETRIC;
2004 // This statement shouldn't be reached, switch cases will always
2005 // cover all possible ColorMode returned by pickColorMode.
2006 default:
2007 return RenderIntent::COLORIMETRIC;
2008 }
2009 }
2010
2011 // Either enhance is not supported or we are in natural mode.
2012
2013 // Natural Mode means it's color managed and the color must be right,
2014 // thus we pick RenderIntent::COLORIMETRIC as render intent for non-HDR
2015 // content and pick RenderIntent::TONE_MAP_COLORIMETRIC for HDR content.
2016 switch (colorMode) {
2017 // In Natural Color Mode, BT2100_PQ and BT2100_HLG will only be picked
2018 // when TONE_MAP_COLORIMETRIC is supported.
2019 case ColorMode::BT2100_PQ:
2020 case ColorMode::BT2100_HLG:
2021 return RenderIntent::TONE_MAP_COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002022 default:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002023 return RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002024 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002025}
2026
Chia-I Wu30505fb2018-03-26 16:20:31 -07002027void SurfaceFlinger::setUpHWComposer() {
2028 ATRACE_CALL();
2029 ALOGV("setUpHWComposer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08002030
Jesse Hall028dc8f2013-08-20 16:35:32 -07002031 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Dan Stozac7a25ad2018-04-12 11:45:09 -07002032 bool dirty = !mDisplays[dpy]->getDirtyRegion(mRepaintEverything).isEmpty();
Jesse Hallb7a05492014-08-14 15:45:06 -07002033 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
2034 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
2035
2036 // If nothing has changed (!dirty), don't recompose.
2037 // If something changed, but we don't currently have any visible layers,
2038 // and didn't when we last did a composition, then skip it this time.
2039 // The second rule does two things:
2040 // - When all layers are removed from a display, we'll emit one black
2041 // frame, then nothing more until we get new layers.
2042 // - When a display is created with a private layer stack, we won't
2043 // emit any black frames until a layer is added to the layer stack.
2044 bool mustRecompose = dirty && !(empty && wasEmpty);
2045
Dominik Laskowski281644e2018-04-19 15:47:35 -07002046 ALOGV_IF(mDisplays[dpy]->isVirtual(),
Jesse Hallb7a05492014-08-14 15:45:06 -07002047 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
2048 mustRecompose ? "doing" : "skipping",
2049 dirty ? "+" : "-",
2050 empty ? "+" : "-",
2051 wasEmpty ? "+" : "-");
2052
Dan Stoza71433162014-02-04 16:22:36 -08002053 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07002054
2055 if (mustRecompose) {
2056 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
2057 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07002058 }
2059
Chia-I Wu30505fb2018-03-26 16:20:31 -07002060 // build the h/w work list
2061 if (CC_UNLIKELY(mGeometryInvalid)) {
2062 mGeometryInvalid = false;
2063 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2064 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
2065 const auto hwcId = displayDevice->getHwcDisplayId();
2066 if (hwcId >= 0) {
2067 const Vector<sp<Layer>>& currentLayers(
2068 displayDevice->getVisibleLayersSortedByZ());
2069 for (size_t i = 0; i < currentLayers.size(); i++) {
2070 const auto& layer = currentLayers[i];
2071 if (!layer->hasHwcLayer(hwcId)) {
2072 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
2073 layer->forceClientComposition(hwcId);
2074 continue;
2075 }
2076 }
2077
2078 layer->setGeometry(displayDevice, i);
2079 if (mDebugDisableHWC || mDebugRegion) {
2080 layer->forceClientComposition(hwcId);
2081 }
2082 }
2083 }
2084 }
2085 }
2086
Chia-I Wu30505fb2018-03-26 16:20:31 -07002087 // Set the per-frame data
2088 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2089 auto& displayDevice = mDisplays[displayId];
2090 const auto hwcId = displayDevice->getHwcDisplayId();
2091
2092 if (hwcId < 0) {
2093 continue;
2094 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07002095 if (mDrawingState.colorMatrixChanged) {
2096 displayDevice->setColorTransform(mDrawingState.colorMatrix);
2097 status_t result = getBE().mHwc->setColorTransform(hwcId, mDrawingState.colorMatrix);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002098 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
2099 "display %zd: %d", displayId, result);
2100 }
2101 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002102 if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2103 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Peiyong Lin62665892018-04-16 11:07:44 -07002104 !displayDevice->hasHDR10Support()) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07002105 layer->forceClientComposition(hwcId);
2106 }
Chia-I Wu01591c92018-05-22 12:03:00 -07002107 if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
2108 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Peiyong Linf59a7192018-04-25 11:19:31 -07002109 !displayDevice->hasHLGSupport()) {
2110 layer->forceClientComposition(hwcId);
2111 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002112
2113 if (layer->getForceClientComposition(hwcId)) {
2114 ALOGV("[%s] Requesting Client composition", layer->getName().string());
2115 layer->setCompositionType(hwcId, HWC2::Composition::Client);
2116 continue;
2117 }
2118
2119 layer->setPerFrameData(displayDevice);
2120 }
2121
2122 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002123 ColorMode colorMode;
2124 Dataspace dataSpace;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002125 RenderIntent renderIntent;
2126 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
2127 setActiveColorModeInternal(displayDevice, colorMode, dataSpace, renderIntent);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002128 }
2129 }
2130
Chia-I Wu28f320b2018-05-03 11:02:56 -07002131 mDrawingState.colorMatrixChanged = false;
Chia-I Wu30505fb2018-03-26 16:20:31 -07002132
Dan Stoza9e56aa02015-11-02 13:00:03 -08002133 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002134 auto& displayDevice = mDisplays[displayId];
2135 if (!displayDevice->isDisplayOn()) {
2136 continue;
2137 }
2138
David Sodman105b7dc2017-11-04 20:28:14 -07002139 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002140 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2141 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002142 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002143}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002144
Mathias Agopiancd60f992012-08-16 16:28:27 -07002145void SurfaceFlinger::doComposition() {
2146 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002147 ALOGV("doComposition");
2148
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002149 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002150 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002151 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002152 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002153 // transform the dirty region into this screen's coordinate space
2154 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002155
2156 // repaint the framebuffer (if needed)
2157 doDisplayComposition(hw, dirtyRegion);
2158
Mathias Agopiancd60f992012-08-16 16:28:27 -07002159 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002160 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002161 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002162 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002163 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002164}
2165
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002166void SurfaceFlinger::postFramebuffer()
2167{
Mathias Agopian841cde52012-03-01 15:44:37 -08002168 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002169 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002170
Mathias Agopiana44b0412011-10-16 18:46:35 -07002171 const nsecs_t now = systemTime();
2172 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002173
Dan Stoza9e56aa02015-11-02 13:00:03 -08002174 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2175 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002176 if (!displayDevice->isDisplayOn()) {
2177 continue;
2178 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002179 const auto hwcId = displayDevice->getHwcDisplayId();
2180 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002181 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002182 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002183 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002184 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002185 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002186 // The layer buffer from the previous frame (if any) is released
2187 // by HWC only when the release fence from this frame (if any) is
2188 // signaled. Always get the release fence from HWC first.
2189 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002190 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002191
2192 // If the layer was client composited in the previous frame, we
2193 // need to merge with the previous client target acquire fence.
2194 // Since we do not track that, always merge with the current
2195 // client target acquire fence when it is available, even though
2196 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002197 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002198 releaseFence = Fence::merge("LayerRelease", releaseFence,
2199 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002200 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002201
David Sodmanb8af7922017-12-21 15:17:55 -08002202 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002203 }
Chia-I Wu83806892017-11-16 10:50:20 -08002204
2205 // We've got a list of layers needing fences, that are disjoint with
2206 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2207 // supply them with the present fence.
2208 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002209 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002210 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002211 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002212 }
2213 }
2214
Dan Stoza9e56aa02015-11-02 13:00:03 -08002215 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002216 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002217 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002218 }
2219
Mathias Agopiana44b0412011-10-16 18:46:35 -07002220 mLastSwapBufferTime = systemTime() - now;
2221 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002222
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002223 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002224 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2225 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2226 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2227 logFrameStats();
2228 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002229 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002230}
2231
Mathias Agopian87baae12012-07-31 12:38:26 -07002232void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002233{
Mathias Agopian841cde52012-03-01 15:44:37 -08002234 ATRACE_CALL();
2235
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002236 // here we keep a copy of the drawing state (that is the state that's
2237 // going to be overwritten by handleTransactionLocked()) outside of
2238 // mStateLock so that the side-effects of the State assignment
2239 // don't happen with mStateLock held (which can cause deadlocks).
2240 State drawingState(mDrawingState);
2241
Mathias Agopianca4d3602011-05-19 15:38:14 -07002242 Mutex::Autolock _l(mStateLock);
2243 const nsecs_t now = systemTime();
2244 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002245
Mathias Agopianca4d3602011-05-19 15:38:14 -07002246 // Here we're guaranteed that some transaction flags are set
2247 // so we can call handleTransactionLocked() unconditionally.
2248 // We call getTransactionFlags(), which will also clear the flags,
2249 // with mStateLock held to guarantee that mCurrentState won't change
2250 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002251
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002252 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002253 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002254 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002255
Mathias Agopianca4d3602011-05-19 15:38:14 -07002256 mLastTransactionTime = systemTime() - now;
2257 mDebugInTransaction = 0;
2258 invalidateHwcGeometry();
2259 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002260}
2261
Lloyd Pique715a2c12017-12-14 17:18:08 -08002262DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002263 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002264 // Figure out whether the event is for the primary display or an
2265 // external display by matching the Hwc display id against one for a
2266 // connected display. If we did not find a match, we then check what
2267 // displays are not already connected to determine the type. If we don't
2268 // have a connected primary display, we assume the new display is meant to
2269 // be the primary display, and then if we don't have an external display,
2270 // we assume it is that.
2271 const auto primaryDisplayId =
2272 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2273 const auto externalDisplayId =
2274 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2275 if (primaryDisplayId && primaryDisplayId == display) {
2276 return DisplayDevice::DISPLAY_PRIMARY;
2277 } else if (externalDisplayId && externalDisplayId == display) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002278 return DisplayDevice::DISPLAY_EXTERNAL;
Lloyd Pique715a2c12017-12-14 17:18:08 -08002279 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2280 return DisplayDevice::DISPLAY_PRIMARY;
2281 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2282 return DisplayDevice::DISPLAY_EXTERNAL;
2283 }
2284
2285 return DisplayDevice::DISPLAY_ID_INVALID;
2286}
2287
Lloyd Piqueba04e622017-12-14 17:11:26 -08002288void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2289 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002290 auto displayType = determineDisplayType(event.display, event.connection);
2291 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2292 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2293 continue;
2294 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002295
2296 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2297 ALOGE("External displays are not supported by the vr hardware composer.");
2298 continue;
2299 }
2300
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002301 const auto displayId =
2302 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
2303 if (displayId) {
2304 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.display, *displayId);
2305 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002306
2307 if (event.connection == HWC2::Connection::Connected) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002308 if (!mBuiltinDisplays[displayType].get()) {
2309 ALOGV("Creating built in display %d", displayType);
2310 mBuiltinDisplays[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002311 DisplayDeviceState info;
2312 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002313 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2314 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002315 info.isSecure = true; // All physical displays are currently considered secure.
Steven Thomaseb6d2052018-03-20 15:40:48 -07002316 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
2317 mInterceptor->saveDisplayCreation(info);
2318 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002319 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002320 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002321
Lloyd Piquefcd86612017-12-14 17:15:36 -08002322 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2323 if (idx >= 0) {
2324 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002325 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002326 mCurrentState.displays.removeItemsAt(idx);
2327 }
2328 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002329 }
2330
2331 processDisplayChangesLocked();
2332 }
2333
2334 mPendingHotplugEvents.clear();
2335}
2336
Lloyd Pique99d3da52018-01-22 17:48:03 -08002337sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2338 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2339 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002340 bool hasWideColorGamut = false;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002341 std::unordered_map<ColorMode, std::vector<RenderIntent>> hdrAndRenderIntents;
2342
Lloyd Pique99d3da52018-01-22 17:48:03 -08002343 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002344 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002345 for (ColorMode colorMode : modes) {
2346 switch (colorMode) {
2347 case ColorMode::DISPLAY_P3:
2348 case ColorMode::ADOBE_RGB:
2349 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002350 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002351 break;
2352 default:
2353 break;
2354 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002355
2356 std::vector<RenderIntent> renderIntents = getHwComposer().getRenderIntents(hwcId,
2357 colorMode);
2358 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2359 for (auto intent : renderIntents) {
2360 if (intent == RenderIntent::ENHANCE) {
2361 mBuiltinDisplaySupportsEnhance = true;
2362 break;
2363 }
2364 }
2365 }
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002366
2367 if (colorMode == ColorMode::BT2100_PQ || colorMode == ColorMode::BT2100_HLG) {
2368 hdrAndRenderIntents.emplace(colorMode, renderIntents);
2369 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002370 }
2371 }
2372
Peiyong Lin62665892018-04-16 11:07:44 -07002373 HdrCapabilities hdrCapabilities;
2374 getHwComposer().getHdrCapabilities(hwcId, &hdrCapabilities);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002375
2376 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2377 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2378
2379 /*
2380 * Create our display's surface
2381 */
2382 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2383 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002384 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002385 renderSurface->setNativeWindow(nativeWindow.get());
2386 const int displayWidth = renderSurface->queryWidth();
2387 const int displayHeight = renderSurface->queryHeight();
2388
2389 // Make sure that composition can never be stalled by a virtual display
2390 // consumer that isn't processing buffers fast enough. We have to do this
2391 // in two places:
2392 // * Here, in case the display is composed entirely by HWC.
2393 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2394 // window's swap interval in eglMakeCurrent, so they'll override the
2395 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002396 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002397 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2398 }
2399
2400 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002401 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002402
2403 sp<DisplayDevice> hw =
2404 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2405 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
Peiyong Lin0ac5f4e2018-04-19 22:06:34 -07002406 hasWideColorGamut, hdrCapabilities,
2407 getHwComposer().getSupportedPerFrameMetadata(hwcId),
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002408 hdrAndRenderIntents, initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002409
2410 if (maxFrameBufferAcquiredBuffers >= 3) {
2411 nativeWindowSurface->preallocateBuffers();
2412 }
2413
2414 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002415 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2416 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002417 defaultColorMode = ColorMode::SRGB;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002418 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002419 }
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002420 setActiveColorModeInternal(hw, defaultColorMode, defaultDataSpace,
2421 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002422 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
2423 hw->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
2424 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002425 hw->setLayerStack(state.layerStack);
2426 hw->setProjection(state.orientation, state.viewport, state.frame);
2427 hw->setDisplayName(state.displayName);
2428
2429 return hw;
2430}
2431
Lloyd Pique347200f2017-12-14 17:00:15 -08002432void SurfaceFlinger::processDisplayChangesLocked() {
2433 // here we take advantage of Vector's copy-on-write semantics to
2434 // improve performance by skipping the transaction entirely when
2435 // know that the lists are identical
2436 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2437 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2438 if (!curr.isIdenticalTo(draw)) {
2439 mVisibleRegionsDirty = true;
2440 const size_t cc = curr.size();
2441 size_t dc = draw.size();
2442
2443 // find the displays that were removed
2444 // (ie: in drawing state but not in current state)
2445 // also handle displays that changed
2446 // (ie: displays that are in both lists)
2447 for (size_t i = 0; i < dc;) {
2448 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2449 if (j < 0) {
2450 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002451 // Call makeCurrent() on the primary display so we can
2452 // be sure that nothing associated with this display
2453 // is current.
2454 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2455 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2456 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2457 if (hw != nullptr) hw->disconnect(getHwComposer());
2458 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2459 mEventThread->onHotplugReceived(draw[i].type, false);
2460 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002461 } else {
2462 // this display is in both lists. see if something changed.
2463 const DisplayDeviceState& state(curr[j]);
2464 const wp<IBinder>& display(curr.keyAt(j));
2465 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2466 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2467 if (state_binder != draw_binder) {
2468 // changing the surface is like destroying and
2469 // recreating the DisplayDevice, so we just remove it
2470 // from the drawing state, so that it get re-added
2471 // below.
2472 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2473 if (hw != nullptr) hw->disconnect(getHwComposer());
2474 mDisplays.removeItem(display);
2475 mDrawingState.displays.removeItemsAt(i);
2476 dc--;
2477 // at this point we must loop to the next item
2478 continue;
2479 }
2480
2481 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2482 if (disp != nullptr) {
2483 if (state.layerStack != draw[i].layerStack) {
2484 disp->setLayerStack(state.layerStack);
2485 }
2486 if ((state.orientation != draw[i].orientation) ||
2487 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2488 disp->setProjection(state.orientation, state.viewport, state.frame);
2489 }
2490 if (state.width != draw[i].width || state.height != draw[i].height) {
2491 disp->setDisplaySize(state.width, state.height);
2492 }
2493 }
2494 }
2495 ++i;
2496 }
2497
2498 // find displays that were added
2499 // (ie: in current state but not in drawing state)
2500 for (size_t i = 0; i < cc; i++) {
2501 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2502 const DisplayDeviceState& state(curr[i]);
2503
2504 sp<DisplaySurface> dispSurface;
2505 sp<IGraphicBufferProducer> producer;
2506 sp<IGraphicBufferProducer> bqProducer;
2507 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002508 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002509
2510 int32_t hwcId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002511 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002512 // Virtual displays without a surface are dormant:
2513 // they have external state (layer stack, projection,
2514 // etc.) but no internal state (i.e. a DisplayDevice).
2515 if (state.surface != nullptr) {
2516 // Allow VR composer to use virtual displays.
2517 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2518 int width = 0;
2519 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2520 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2521 int height = 0;
2522 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2523 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2524 int intFormat = 0;
2525 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2526 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002527 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002528
2529 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2530 }
2531
2532 // TODO: Plumb requested format back up to consumer
2533
2534 sp<VirtualDisplaySurface> vds =
2535 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2536 bqProducer, bqConsumer,
2537 state.displayName);
2538
2539 dispSurface = vds;
2540 producer = vds;
2541 }
2542 } else {
2543 ALOGE_IF(state.surface != nullptr,
2544 "adding a supported display, but rendering "
2545 "surface is provided (%p), ignoring it",
2546 state.surface.get());
2547
2548 hwcId = state.type;
2549 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2550 producer = bqProducer;
2551 }
2552
2553 const wp<IBinder>& display(curr.keyAt(i));
2554 if (dispSurface != nullptr) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002555 mDisplays.add(display,
2556 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2557 producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002558 if (!state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002559 mEventThread->onHotplugReceived(state.type, true);
2560 }
2561 }
2562 }
2563 }
2564 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002565
2566 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002567}
2568
Mathias Agopian87baae12012-07-31 12:38:26 -07002569void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002570{
Dan Stoza7dde5992015-05-22 09:51:44 -07002571 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002572 mCurrentState.traverseInZOrder([](Layer* layer) {
2573 layer->notifyAvailableFrames();
2574 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002575
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002576 /*
2577 * Traversal of the children
2578 * (perform the transaction for each of them if needed)
2579 */
2580
Mathias Agopian3559b072012-08-15 13:46:03 -07002581 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002582 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002583 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002584 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002585
2586 const uint32_t flags = layer->doTransaction(0);
2587 if (flags & Layer::eVisibleRegion)
2588 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002589 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002590 }
2591
2592 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002593 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002594 */
2595
Mathias Agopiane57f2922012-08-09 16:29:12 -07002596 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002597 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002598 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002599 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002600
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002601 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002602 // The transform hint might have changed for some layers
2603 // (either because a display has changed, or because a layer
2604 // as changed).
2605 //
2606 // Walk through all the layers in currentLayers,
2607 // and update their transform hint.
2608 //
2609 // If a layer is visible only on a single display, then that
2610 // display is used to calculate the hint, otherwise we use the
2611 // default display.
2612 //
2613 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2614 // the hint is set before we acquire a buffer from the surface texture.
2615 //
2616 // NOTE: layer transactions have taken place already, so we use their
2617 // drawing state. However, SurfaceFlinger's own transaction has not
2618 // happened yet, so we must use the current state layer list
2619 // (soon to become the drawing state list).
2620 //
2621 sp<const DisplayDevice> disp;
2622 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002623 bool first = true;
2624 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002625 // NOTE: we rely on the fact that layers are sorted by
2626 // layerStack first (so we don't have to traverse the list
2627 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002628 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002629 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002630 currentlayerStack = layerStack;
2631 // figure out if this layerstack is mirrored
2632 // (more than one display) if so, pick the default display,
2633 // if not, pick the only display it's on.
2634 disp.clear();
2635 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2636 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002637 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002638 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002639 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002640 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002641 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002642 break;
2643 }
2644 }
2645 }
2646 }
Chet Haase91d25932013-04-11 15:24:55 -07002647
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002648 if (disp == nullptr) {
2649 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2650 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002651
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002652 // could be null when this layer is using a layerStack
2653 // that is not visible on any display. Also can occur at
2654 // screen off/on times.
2655 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002656 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002657
2658 // disp can be null if there is no display available at all to get
2659 // the transform hint from.
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002660 if (disp != nullptr) {
2661 layer->updateTransformHint(disp);
2662 }
Robert Carr2047fae2016-11-28 14:09:09 -08002663
2664 first = false;
2665 });
Mathias Agopian84300952012-11-21 16:02:13 -08002666 }
2667
2668
Mathias Agopian3559b072012-08-15 13:46:03 -07002669 /*
2670 * Perform our own transaction if needed
2671 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002672
2673 if (mLayersAdded) {
2674 mLayersAdded = false;
2675 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002676 mVisibleRegionsDirty = true;
2677 }
2678
2679 // some layers might have been removed, so
2680 // we need to update the regions they're exposing.
2681 if (mLayersRemoved) {
2682 mLayersRemoved = false;
2683 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002684 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002685 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002686 // this layer is not visible anymore
2687 // TODO: we could traverse the tree from front to back and
2688 // compute the actual visible region
2689 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002690 Region visibleReg;
2691 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002692 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002693 }
Robert Carr2047fae2016-11-28 14:09:09 -08002694 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002695 }
2696
2697 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002698
2699 updateCursorAsync();
2700}
2701
2702void SurfaceFlinger::updateCursorAsync()
2703{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002704 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2705 auto& displayDevice = mDisplays[displayId];
2706 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002707 continue;
2708 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002709
2710 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2711 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002712 }
2713 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002714}
2715
2716void SurfaceFlinger::commitTransaction()
2717{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002718 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002719 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002720 for (const auto& l : mLayersPendingRemoval) {
2721 recordBufferingStats(l->getName().string(),
2722 l->getOccupancyHistory(true));
2723 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002724 }
2725 mLayersPendingRemoval.clear();
2726 }
2727
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002728 // If this transaction is part of a window animation then the next frame
2729 // we composite should be considered an animation as well.
2730 mAnimCompositionPending = mAnimTransactionPending;
2731
Mathias Agopian4fec8732012-06-29 14:12:52 -07002732 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002733 // clear the "changed" flags in current state
2734 mCurrentState.colorMatrixChanged = false;
2735
Robert Carr1f0a16a2016-10-24 16:27:39 -07002736 mDrawingState.traverseInZOrder([](Layer* layer) {
2737 layer->commitChildList();
2738 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002739 mTransactionPending = false;
2740 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002741 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002742}
2743
Chia-I Wuab0c3192017-08-01 11:29:00 -07002744void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002745 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002746{
Mathias Agopian841cde52012-03-01 15:44:37 -08002747 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002748 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002749
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002750 Region aboveOpaqueLayers;
2751 Region aboveCoveredLayers;
2752 Region dirty;
2753
Mathias Agopian87baae12012-07-31 12:38:26 -07002754 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002755
Robert Carr2047fae2016-11-28 14:09:09 -08002756 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002757 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002758 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002759
Jesse Hall01e29052013-02-19 16:13:35 -08002760 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002761 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002762 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002763
Mathias Agopianab028732010-03-16 16:41:46 -07002764 /*
2765 * opaqueRegion: area of a surface that is fully opaque.
2766 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002767 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002768
2769 /*
2770 * visibleRegion: area of a surface that is visible on screen
2771 * and not fully transparent. This is essentially the layer's
2772 * footprint minus the opaque regions above it.
2773 * Areas covered by a translucent surface are considered visible.
2774 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002775 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002776
2777 /*
2778 * coveredRegion: area of a surface that is covered by all
2779 * visible regions above it (which includes the translucent areas).
2780 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002781 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002782
Jesse Halla8026d22012-09-25 13:25:04 -07002783 /*
2784 * transparentRegion: area of a surface that is hinted to be completely
2785 * transparent. This is only used to tell when the layer has no visible
2786 * non-transparent regions and can be removed from the layer list. It
2787 * does not affect the visibleRegion of this layer or any layers
2788 * beneath it. The hint may not be correct if apps don't respect the
2789 * SurfaceView restrictions (which, sadly, some don't).
2790 */
2791 Region transparentRegion;
2792
Mathias Agopianab028732010-03-16 16:41:46 -07002793
2794 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002795 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002796 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002797 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002798 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002799 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002800 if (!visibleRegion.isEmpty()) {
2801 // Remove the transparent area from the visible region
2802 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002803 if (tr.preserveRects()) {
2804 // transform the transparent region
2805 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002806 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002807 // transformation too complex, can't do the
2808 // transparent region optimization.
2809 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002810 }
Mathias Agopianab028732010-03-16 16:41:46 -07002811 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002812
Mathias Agopianab028732010-03-16 16:41:46 -07002813 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002814 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002815 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002816 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2817 // the opaque region is the layer's footprint
2818 opaqueRegion = visibleRegion;
2819 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002820 }
2821 }
2822
Robert Carre5f4f692018-01-12 13:12:28 -08002823 if (visibleRegion.isEmpty()) {
2824 layer->clearVisibilityRegions();
2825 return;
2826 }
2827
Mathias Agopianab028732010-03-16 16:41:46 -07002828 // Clip the covered region to the visible region
2829 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2830
2831 // Update aboveCoveredLayers for next (lower) layer
2832 aboveCoveredLayers.orSelf(visibleRegion);
2833
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002834 // subtract the opaque region covered by the layers above us
2835 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002836
2837 // compute this layer's dirty region
2838 if (layer->contentDirty) {
2839 // we need to invalidate the whole region
2840 dirty = visibleRegion;
2841 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002842 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002843 layer->contentDirty = false;
2844 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002845 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002846 * the exposed region consists of two components:
2847 * 1) what's VISIBLE now and was COVERED before
2848 * 2) what's EXPOSED now less what was EXPOSED before
2849 *
2850 * note that (1) is conservative, we start with the whole
2851 * visible region but only keep what used to be covered by
2852 * something -- which mean it may have been exposed.
2853 *
2854 * (2) handles areas that were not covered by anything but got
2855 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002856 */
Mathias Agopianab028732010-03-16 16:41:46 -07002857 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002858 const Region oldVisibleRegion = layer->visibleRegion;
2859 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002860 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2861 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002862 }
2863 dirty.subtractSelf(aboveOpaqueLayers);
2864
2865 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002866 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002867
Mathias Agopianab028732010-03-16 16:41:46 -07002868 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002869 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002870
Jesse Halla8026d22012-09-25 13:25:04 -07002871 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002872 layer->setVisibleRegion(visibleRegion);
2873 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002874 layer->setVisibleNonTransparentRegion(
2875 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002876 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002877
Mathias Agopian87baae12012-07-31 12:38:26 -07002878 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002879}
2880
Chia-I Wuab0c3192017-08-01 11:29:00 -07002881void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002882 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002883 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002884 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002885 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002886 }
2887 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002888}
2889
Dan Stoza6b9454d2014-11-07 16:00:59 -08002890bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002891{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002892 ALOGV("handlePageFlip");
2893
Brian Andersond6927fb2016-07-23 23:37:30 -07002894 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002895
Mathias Agopian4fec8732012-06-29 14:12:52 -07002896 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002897 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002898 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002899
2900 // Store the set of layers that need updates. This set must not change as
2901 // buffers are being latched, as this could result in a deadlock.
2902 // Example: Two producers share the same command stream and:
2903 // 1.) Layer 0 is latched
2904 // 2.) Layer 0 gets a new frame
2905 // 2.) Layer 1 gets a new frame
2906 // 3.) Layer 1 is latched.
2907 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2908 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002909 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002910 if (layer->hasQueuedFrame()) {
2911 frameQueued = true;
2912 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002913 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002914 } else {
2915 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002916 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002917 } else {
2918 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002919 }
Robert Carr2047fae2016-11-28 14:09:09 -08002920 });
2921
Dan Stoza9e56aa02015-11-02 13:00:03 -08002922 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002923 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002924 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002925 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002926 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002927 newDataLatched = true;
2928 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002929 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002930
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002931 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002932
2933 // If we will need to wake up at some time in the future to deal with a
2934 // queued frame that shouldn't be displayed during this vsync period, wake
2935 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002936 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002937 signalLayerUpdate();
2938 }
2939
2940 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002941 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002942}
2943
Mathias Agopianad456f92011-01-13 17:53:01 -08002944void SurfaceFlinger::invalidateHwcGeometry()
2945{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002946 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002947}
2948
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002949
Fabien Sanglard830b8472016-11-30 16:35:58 -08002950void SurfaceFlinger::doDisplayComposition(
2951 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002952 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002953{
Dan Stoza71433162014-02-04 16:22:36 -08002954 // We only need to actually compose the display if:
2955 // 1) It is being handled by hardware composer, which may need this to
2956 // keep its virtual display state machine in sync, or
2957 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002958 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002959 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002960 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002961 return;
2962 }
2963
Dan Stoza9e56aa02015-11-02 13:00:03 -08002964 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002965 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002966
2967 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002968 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002969}
2970
Chia-I Wub02087d2017-11-09 10:19:54 -08002971bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002972{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002973 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002974
Chia-I Wub02087d2017-11-09 10:19:54 -08002975 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002976 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002977 const auto hwcId = displayDevice->getHwcDisplayId();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002978 const bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002979 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002980
Chia-I Wu8e50e692018-05-04 10:12:37 -07002981 bool applyColorMatrix = false;
Peiyong Lin00f9c022018-05-09 15:35:33 -07002982 bool needsLegacyColorMatrix = false;
2983 bool legacyColorMatrixApplied = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002984
Dan Stoza9e56aa02015-11-02 13:00:03 -08002985 if (hasClientComposition) {
2986 ALOGV("hasClientComposition");
2987
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002988 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002989 if (displayDevice->hasWideColorGamut()) {
2990 outputDataspace = displayDevice->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002991 }
2992 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002993 getBE().mRenderEngine->setDisplayMaxLuminance(
2994 displayDevice->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002995
Chia-I Wu8e50e692018-05-04 10:12:37 -07002996 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
2997 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2998 HWC2::Capability::SkipClientColorTransform);
2999
3000 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3001 if (applyColorMatrix) {
Peiyong Lin00f9c022018-05-09 15:35:33 -07003002 getRenderEngine().setupColorTransform(mDrawingState.colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003003 }
3004
Peiyong Lin00f9c022018-05-09 15:35:33 -07003005 needsLegacyColorMatrix = (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07003006 outputDataspace != Dataspace::UNKNOWN &&
3007 outputDataspace != Dataspace::SRGB);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003008
Chia-I Wu7f402902017-11-09 12:51:10 -08003009 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003010 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskibf170d92018-04-19 15:08:05 -07003011 displayDevice->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08003012 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003013
3014 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08003015 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07003016 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
3017 }
3018 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003019 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003020
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003021 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003022 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003023 // when using overlays, we assume a fully transparent framebuffer
3024 // NOTE: we could reduce how much we need to clear, for instance
3025 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003026 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003027 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003028 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003029 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003030 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003031 // we're left with the letterbox region
3032 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08003033 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07003034
3035 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08003036 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07003037
Mathias Agopianb9494d52012-04-18 02:28:45 -07003038 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003039 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003040 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08003041 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003042 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003043 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003044
Dominik Laskowski281644e2018-04-19 15:47:35 -07003045 if (!displayDevice->isPrimary()) {
Mathias Agopian766dc492012-10-30 18:08:06 -07003046 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07003047 // scissor on the main display. It should never be needed
3048 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08003049 const Rect& bounds(displayDevice->getBounds());
3050 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003051 if (scissor != bounds) {
3052 // scissor doesn't match the screen's dimensions, so we
3053 // need to clear everything outside of it and enable
3054 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003055
Mathias Agopianf45c5102012-10-24 16:29:17 -07003056 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08003057 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08003058 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07003059 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003060 }
3061 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003062 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003063
Mathias Agopian85d751c2012-08-29 16:59:24 -07003064 /*
3065 * and then, render the layers targeted at the framebuffer
3066 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003067
Dan Stoza9e56aa02015-11-02 13:00:03 -08003068 ALOGV("Rendering client layers");
3069 const Transform& displayTransform = displayDevice->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003070 bool firstLayer = true;
3071 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
3072 const Region clip(bounds.intersect(
3073 displayTransform.transform(layer->visibleRegion)));
3074 ALOGV("Layer: %s", layer->getName().string());
3075 ALOGV(" Composition type: %s",
3076 to_string(layer->getCompositionType(hwcId)).c_str());
3077 if (!clip.isEmpty()) {
3078 switch (layer->getCompositionType(hwcId)) {
3079 case HWC2::Composition::Cursor:
3080 case HWC2::Composition::Device:
3081 case HWC2::Composition::Sideband:
3082 case HWC2::Composition::SolidColor: {
3083 const Layer::State& state(layer->getDrawingState());
3084 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
3085 layer->isOpaque(state) && (state.color.a == 1.0f)
3086 && hasClientComposition) {
3087 // never clear the very first layer since we're
3088 // guaranteed the FB is already cleared
3089 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003090 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003091 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003092 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003093 case HWC2::Composition::Client: {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003094 // switch color matrices lazily
Peiyong Lin00f9c022018-05-09 15:35:33 -07003095 if (layer->isLegacyDataSpace() && needsLegacyColorMatrix) {
3096 if (!legacyColorMatrixApplied) {
3097 getRenderEngine().setSaturationMatrix(mLegacySrgbSaturationMatrix);
3098 legacyColorMatrixApplied = true;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003099 }
Peiyong Lin00f9c022018-05-09 15:35:33 -07003100 } else if (legacyColorMatrixApplied) {
3101 getRenderEngine().setSaturationMatrix(mat4());
3102 legacyColorMatrixApplied = false;
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003103 }
Chia-I Wu8e50e692018-05-04 10:12:37 -07003104
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003105 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003106 break;
3107 }
3108 default:
3109 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003110 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003111 } else {
3112 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003113 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003114 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003115 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003116
Peiyong Lin00f9c022018-05-09 15:35:33 -07003117 if (applyColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003118 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003119 }
Peiyong Lin00f9c022018-05-09 15:35:33 -07003120 if (needsLegacyColorMatrix && legacyColorMatrixApplied) {
3121 getRenderEngine().setSaturationMatrix(mat4());
3122 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003123
Mathias Agopianf45c5102012-10-24 16:29:17 -07003124 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003125 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003126 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003127}
3128
Fabien Sanglard830b8472016-11-30 16:35:58 -08003129void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
3130 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003131 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003132 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003133}
3134
Dan Stoza7d89d062015-04-30 13:29:25 -07003135status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003136 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003137 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003138 const sp<Layer>& lbc,
3139 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003140{
Dan Stoza7d89d062015-04-30 13:29:25 -07003141 // add this layer to the current state list
3142 {
3143 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003144 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003145 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3146 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003147 return NO_MEMORY;
3148 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003149 if (parent == nullptr) {
3150 mCurrentState.layersSortedByZ.add(lbc);
3151 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003152 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003153 ALOGE("addClientLayer called with a removed parent");
3154 return NAME_NOT_FOUND;
3155 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003156 parent->addChild(lbc);
3157 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003158
Yiwei Zhang243b3782018-05-15 17:40:04 -07003159 if (gbc != nullptr) {
3160 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3161 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3162 mMaxGraphicBufferProducerListSize,
3163 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3164 mGraphicBufferProducerList.size(),
3165 mMaxGraphicBufferProducerListSize, mNumLayers);
3166 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003167 mLayersAdded = true;
3168 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003169 }
3170
Mathias Agopian96f08192010-06-02 23:28:45 -07003171 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003172 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003173
Dan Stoza7d89d062015-04-30 13:29:25 -07003174 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003175}
3176
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003177status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003178 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003179 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3180}
Robert Carr7f9b8992017-03-10 11:08:39 -08003181
chaviwca27f252018-02-06 16:46:39 -08003182status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3183 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003184 if (layer->isPendingRemoval()) {
3185 return NO_ERROR;
3186 }
3187
Robert Carr1f0a16a2016-10-24 16:27:39 -07003188 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003189 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003190 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003191 if (topLevelOnly) {
3192 return NO_ERROR;
3193 }
3194
Chia-I Wu98f1c102017-05-30 14:54:08 -07003195 sp<Layer> ancestor = p;
3196 while (ancestor->getParent() != nullptr) {
3197 ancestor = ancestor->getParent();
3198 }
3199 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3200 ALOGE("removeLayer called with a layer whose parent has been removed");
3201 return NAME_NOT_FOUND;
3202 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003203
3204 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003205 } else {
3206 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003207 }
3208
Robert Carr136e2f62017-02-08 17:54:29 -08003209 // As a matter of normal operation, the LayerCleaner will produce a second
3210 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3211 // so we will succeed in promoting it, but it's already been removed
3212 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3213 // otherwise something has gone wrong and we are leaking the layer.
3214 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003215 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3216 layer->getName().string(),
3217 (p != nullptr) ? p->getName().string() : "no-parent");
3218 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003219 } else if (index < 0) {
3220 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003221 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003222
Chia-I Wuc6657022017-08-15 11:18:17 -07003223 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003224 mLayersPendingRemoval.add(layer);
3225 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003226 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003227 setTransactionFlags(eTransactionNeeded);
3228 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003229}
3230
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003231uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003232 return android_atomic_release_load(&mTransactionFlags);
3233}
3234
Mathias Agopian3f844832013-08-07 21:24:32 -07003235uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003236 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3237}
3238
Mathias Agopian3f844832013-08-07 21:24:32 -07003239uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003240 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3241}
3242
3243uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3244 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003245 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003246 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003247 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003248 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003249 }
3250 return old;
3251}
3252
chaviwca27f252018-02-06 16:46:39 -08003253bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3254 for (const ComposerState& state : states) {
3255 // Here we need to check that the interface we're given is indeed
3256 // one of our own. A malicious client could give us a nullptr
3257 // IInterface, or one of its own or even one of our own but a
3258 // different type. All these situations would cause us to crash.
3259 if (state.client == nullptr) {
3260 return true;
3261 }
3262
3263 sp<IBinder> binder = IInterface::asBinder(state.client);
3264 if (binder == nullptr) {
3265 return true;
3266 }
3267
3268 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3269 return true;
3270 }
3271 }
3272 return false;
3273}
3274
Mathias Agopian8b33f032012-07-24 20:43:54 -07003275void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003276 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003277 const Vector<DisplayState>& displays,
3278 uint32_t flags)
3279{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003280 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003281 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003282 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003283
chaviwca27f252018-02-06 16:46:39 -08003284 if (containsAnyInvalidClientState(states)) {
3285 return;
3286 }
3287
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003288 if (flags & eAnimation) {
3289 // For window updates that are part of an animation we must wait for
3290 // previous animation "frames" to be handled.
3291 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003292 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003293 if (CC_UNLIKELY(err != NO_ERROR)) {
3294 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003295 // caller after a few seconds.
3296 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3297 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003298 mAnimTransactionPending = false;
3299 break;
3300 }
3301 }
3302 }
3303
chaviwca27f252018-02-06 16:46:39 -08003304 for (const DisplayState& display : displays) {
3305 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003306 }
3307
chaviwca27f252018-02-06 16:46:39 -08003308 for (const ComposerState& state : states) {
3309 transactionFlags |= setClientStateLocked(state);
3310 }
3311
3312 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3313 // as destroyed should only occur after setting all other states. This is to allow for a
3314 // child re-parent to happen before marking its original parent as destroyed (which would
3315 // then mark the child as destroyed).
3316 for (const ComposerState& state : states) {
3317 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003318 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003319
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003320 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3321 // anyway. This can be used as a flush mechanism for previous async transactions.
3322 // Empty animation transaction can be used to simulate back-pressure, so also force a
3323 // transaction for empty animation transactions.
3324 if (transactionFlags == 0 &&
3325 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003326 transactionFlags = eTransactionNeeded;
3327 }
3328
Mathias Agopian386aa982011-11-07 21:58:03 -08003329 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003330 if (mInterceptor->isEnabled()) {
3331 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003332 }
Irvel468051e2016-06-13 16:44:44 -07003333
Mathias Agopian386aa982011-11-07 21:58:03 -08003334 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003335 const auto start = (flags & eEarlyWakeup)
3336 ? VSyncModulator::TransactionStart::EARLY
3337 : VSyncModulator::TransactionStart::NORMAL;
3338 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003339
3340 // if this is a synchronous transaction, wait for it to take effect
3341 // before returning.
3342 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003343 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003344 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003345 if (flags & eAnimation) {
3346 mAnimTransactionPending = true;
3347 }
3348 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003349 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3350 if (CC_UNLIKELY(err != NO_ERROR)) {
3351 // just in case something goes wrong in SF, return to the
3352 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003353 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3354 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003355 break;
3356 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003357 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003358 }
3359}
3360
Mathias Agopiane57f2922012-08-09 16:29:12 -07003361uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3362{
Jesse Hall9a143922012-10-04 16:29:19 -07003363 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3364 if (dpyIdx < 0)
3365 return 0;
3366
Mathias Agopiane57f2922012-08-09 16:29:12 -07003367 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003368 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003369 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003370 const uint32_t what = s.what;
3371 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003372 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003373 disp.surface = s.surface;
3374 flags |= eDisplayTransactionNeeded;
3375 }
3376 }
3377 if (what & DisplayState::eLayerStackChanged) {
3378 if (disp.layerStack != s.layerStack) {
3379 disp.layerStack = s.layerStack;
3380 flags |= eDisplayTransactionNeeded;
3381 }
3382 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003383 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003384 if (disp.orientation != s.orientation) {
3385 disp.orientation = s.orientation;
3386 flags |= eDisplayTransactionNeeded;
3387 }
3388 if (disp.frame != s.frame) {
3389 disp.frame = s.frame;
3390 flags |= eDisplayTransactionNeeded;
3391 }
3392 if (disp.viewport != s.viewport) {
3393 disp.viewport = s.viewport;
3394 flags |= eDisplayTransactionNeeded;
3395 }
3396 }
Michael Lentine47e45402014-07-18 15:34:25 -07003397 if (what & DisplayState::eDisplaySizeChanged) {
3398 if (disp.width != s.width) {
3399 disp.width = s.width;
3400 flags |= eDisplayTransactionNeeded;
3401 }
3402 if (disp.height != s.height) {
3403 disp.height = s.height;
3404 flags |= eDisplayTransactionNeeded;
3405 }
3406 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003407 }
3408 return flags;
3409}
3410
chaviwca27f252018-02-06 16:46:39 -08003411uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3412 const layer_state_t& s = composerState.state;
3413 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3414
Mathias Agopian13127d82013-03-05 17:47:11 -08003415 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003416 if (layer == nullptr) {
3417 return 0;
3418 }
3419
3420 if (layer->isPendingRemoval()) {
3421 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3422 return 0;
3423 }
3424
3425 uint32_t flags = 0;
3426
3427 const uint32_t what = s.what;
3428 bool geometryAppliesWithResize =
3429 what & layer_state_t::eGeometryAppliesWithResize;
3430 if (what & layer_state_t::ePositionChanged) {
3431 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3432 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003433 }
chaviw8b3871a2017-11-01 17:41:01 -07003434 }
3435 if (what & layer_state_t::eLayerChanged) {
3436 // NOTE: index needs to be calculated before we update the state
3437 const auto& p = layer->getParent();
3438 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003439 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003440 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003441 mCurrentState.layersSortedByZ.removeAt(idx);
3442 mCurrentState.layersSortedByZ.add(layer);
3443 // we need traversal (state changed)
3444 // AND transaction (list changed)
3445 flags |= eTransactionNeeded|eTraversalNeeded;
3446 }
chaviw8b3871a2017-11-01 17:41:01 -07003447 } else {
3448 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003449 flags |= eTransactionNeeded|eTraversalNeeded;
3450 }
3451 }
chaviw8b3871a2017-11-01 17:41:01 -07003452 }
3453 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003454 // NOTE: index needs to be calculated before we update the state
3455 const auto& p = layer->getParent();
3456 if (p == nullptr) {
3457 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3458 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3459 mCurrentState.layersSortedByZ.removeAt(idx);
3460 mCurrentState.layersSortedByZ.add(layer);
3461 // we need traversal (state changed)
3462 // AND transaction (list changed)
3463 flags |= eTransactionNeeded|eTraversalNeeded;
3464 }
3465 } else {
3466 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3467 flags |= eTransactionNeeded|eTraversalNeeded;
3468 }
chaviw8b3871a2017-11-01 17:41:01 -07003469 }
3470 }
3471 if (what & layer_state_t::eSizeChanged) {
3472 if (layer->setSize(s.w, s.h)) {
3473 flags |= eTraversalNeeded;
3474 }
3475 }
3476 if (what & layer_state_t::eAlphaChanged) {
3477 if (layer->setAlpha(s.alpha))
3478 flags |= eTraversalNeeded;
3479 }
3480 if (what & layer_state_t::eColorChanged) {
3481 if (layer->setColor(s.color))
3482 flags |= eTraversalNeeded;
3483 }
3484 if (what & layer_state_t::eMatrixChanged) {
3485 if (layer->setMatrix(s.matrix))
3486 flags |= eTraversalNeeded;
3487 }
3488 if (what & layer_state_t::eTransparentRegionChanged) {
3489 if (layer->setTransparentRegionHint(s.transparentRegion))
3490 flags |= eTraversalNeeded;
3491 }
3492 if (what & layer_state_t::eFlagsChanged) {
3493 if (layer->setFlags(s.flags, s.mask))
3494 flags |= eTraversalNeeded;
3495 }
3496 if (what & layer_state_t::eCropChanged) {
3497 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3498 flags |= eTraversalNeeded;
3499 }
3500 if (what & layer_state_t::eFinalCropChanged) {
3501 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3502 flags |= eTraversalNeeded;
3503 }
3504 if (what & layer_state_t::eLayerStackChanged) {
3505 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3506 // We only allow setting layer stacks for top level layers,
3507 // everything else inherits layer stack from its parent.
3508 if (layer->hasParent()) {
3509 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3510 layer->getName().string());
3511 } else if (idx < 0) {
3512 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3513 "that also does not appear in the top level layer list. Something"
3514 " has gone wrong.", layer->getName().string());
3515 } else if (layer->setLayerStack(s.layerStack)) {
3516 mCurrentState.layersSortedByZ.removeAt(idx);
3517 mCurrentState.layersSortedByZ.add(layer);
3518 // we need traversal (state changed)
3519 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003520 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003521 }
3522 }
3523 if (what & layer_state_t::eDeferTransaction) {
3524 if (s.barrierHandle != nullptr) {
3525 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3526 } else if (s.barrierGbp != nullptr) {
3527 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3528 if (authenticateSurfaceTextureLocked(gbp)) {
3529 const auto& otherLayer =
3530 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3531 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3532 } else {
3533 ALOGE("Attempt to defer transaction to to an"
3534 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003535 }
3536 }
chaviw8b3871a2017-11-01 17:41:01 -07003537 // We don't trigger a traversal here because if no other state is
3538 // changed, we don't want this to cause any more work
3539 }
3540 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003541 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003542 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003543 if (!hadParent) {
3544 mCurrentState.layersSortedByZ.remove(layer);
3545 }
chaviw8b3871a2017-11-01 17:41:01 -07003546 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003547 }
chaviw8b3871a2017-11-01 17:41:01 -07003548 }
3549 if (what & layer_state_t::eReparentChildren) {
3550 if (layer->reparentChildren(s.reparentHandle)) {
3551 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003552 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003553 }
chaviw8b3871a2017-11-01 17:41:01 -07003554 if (what & layer_state_t::eDetachChildren) {
3555 layer->detachChildren();
3556 }
3557 if (what & layer_state_t::eOverrideScalingModeChanged) {
3558 layer->setOverrideScalingMode(s.overrideScalingMode);
3559 // We don't trigger a traversal here because if no other state is
3560 // changed, we don't want this to cause any more work
3561 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003562 return flags;
3563}
3564
chaviwca27f252018-02-06 16:46:39 -08003565void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3566 const layer_state_t& state = composerState.state;
3567 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3568
3569 sp<Layer> layer(client->getLayerUser(state.surface));
3570 if (layer == nullptr) {
3571 return;
3572 }
3573
3574 if (layer->isPendingRemoval()) {
3575 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3576 return;
3577 }
3578
3579 if (state.what & layer_state_t::eDestroySurface) {
3580 removeLayerLocked(mStateLock, layer);
3581 }
3582}
3583
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003584status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003585 const String8& name,
3586 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003587 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003588 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003589 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003590{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003591 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003592 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003593 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003594 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003595 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003596
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003597 status_t result = NO_ERROR;
3598
3599 sp<Layer> layer;
3600
Cody Northropbc755282017-03-31 12:00:08 -06003601 String8 uniqueName = getUniqueLayerName(name);
3602
Mathias Agopian3165cc22012-08-08 19:42:09 -07003603 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3604 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003605 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003606 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003607 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003608
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003609 break;
chaviw13fdc492017-06-27 12:40:18 -07003610 case ISurfaceComposerClient::eFXSurfaceColor:
3611 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003612 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003613 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003614 break;
3615 default:
3616 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003617 break;
3618 }
3619
Dan Stoza7d89d062015-04-30 13:29:25 -07003620 if (result != NO_ERROR) {
3621 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003622 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003623
Chia-I Wuab0c3192017-08-01 11:29:00 -07003624 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3625 // TODO b/64227542
3626 if (windowType == 441731) {
3627 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3628 layer->setPrimaryDisplayOnly();
3629 }
3630
Albert Chaulk479c60c2017-01-27 14:21:34 -05003631 layer->setInfo(windowType, ownerUid);
3632
Robert Carr1f0a16a2016-10-24 16:27:39 -07003633 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003634 if (result != NO_ERROR) {
3635 return result;
3636 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003637 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003638
3639 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003640 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003641}
3642
Cody Northropbc755282017-03-31 12:00:08 -06003643String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3644{
3645 bool matchFound = true;
3646 uint32_t dupeCounter = 0;
3647
3648 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3649 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3650
3651 // Loop over layers until we're sure there is no matching name
3652 while (matchFound) {
3653 matchFound = false;
3654 mDrawingState.traverseInZOrder([&](Layer* layer) {
3655 if (layer->getName() == uniqueName) {
3656 matchFound = true;
3657 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3658 }
3659 });
3660 }
3661
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003662 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3663 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003664
3665 return uniqueName;
3666}
3667
David Sodman0c69cad2017-08-21 12:12:51 -07003668status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003669 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3670 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003671{
3672 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003673 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003674 case PIXEL_FORMAT_TRANSPARENT:
3675 case PIXEL_FORMAT_TRANSLUCENT:
3676 format = PIXEL_FORMAT_RGBA_8888;
3677 break;
3678 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003679 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003680 break;
3681 }
3682
David Sodman0c69cad2017-08-21 12:12:51 -07003683 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3684 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003685 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003686 *handle = layer->getHandle();
3687 *gbp = layer->getProducer();
3688 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003689 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003690
David Sodman0c69cad2017-08-21 12:12:51 -07003691 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003692 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003693}
3694
chaviw13fdc492017-06-27 12:40:18 -07003695status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003696 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003697 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003698{
chaviw13fdc492017-06-27 12:40:18 -07003699 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003700 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003701 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003702}
3703
Mathias Agopianac9fa422013-02-11 16:40:36 -08003704status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003705{
Robert Carr9524cb32017-02-13 11:32:32 -08003706 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003707 status_t err = NO_ERROR;
3708 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003709 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003710 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003711 err = removeLayer(l);
3712 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3713 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003714 }
3715 return err;
3716}
3717
Mathias Agopian13127d82013-03-05 17:47:11 -08003718status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003719{
Mathias Agopian67106042013-03-14 19:18:13 -07003720 // called by ~LayerCleaner() when all references to the IBinder (handle)
3721 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003722 sp<Layer> l = layer.promote();
3723 if (l == nullptr) {
3724 // The layer has already been removed, carry on
3725 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003726 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003727 // If we have a parent, then we can continue to live as long as it does.
3728 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003729}
3730
Mathias Agopianb60314a2012-04-10 22:09:54 -07003731// ---------------------------------------------------------------------------
3732
Andy McFadden13a082e2012-08-24 10:16:42 -07003733void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003734 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003735 Vector<ComposerState> state;
3736 Vector<DisplayState> displays;
3737 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003738 d.what = DisplayState::eDisplayProjectionChanged |
3739 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003740 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003741 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003742 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003743 d.frame.makeInvalid();
3744 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003745 d.width = 0;
3746 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003747 displays.add(d);
3748 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003749 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3750 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003751
David Sodman105b7dc2017-11-04 20:28:14 -07003752 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003753 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003754 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003755
Brian Andersond0010582017-03-07 13:20:31 -08003756 // Use phase of 0 since phase is not known.
3757 // Use latency of 0, which will snap to the ideal latency.
3758 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003759}
3760
3761void SurfaceFlinger::initializeDisplays() {
3762 class MessageScreenInitialized : public MessageBase {
3763 SurfaceFlinger* flinger;
3764 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003765 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003766 virtual bool handler() {
3767 flinger->onInitializeDisplays();
3768 return true;
3769 }
3770 };
3771 sp<MessageBase> msg = new MessageScreenInitialized(this);
3772 postMessageAsync(msg); // we may be called from main thread, use async message
3773}
3774
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003775void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003776 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003777 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3778 this);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003779 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003780
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003781 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003782 return;
3783 }
3784
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003785 hw->setPowerMode(mode);
Dominik Laskowski281644e2018-04-19 15:47:35 -07003786 if (hw->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003787 ALOGW("Trying to set power mode for virtual display");
3788 return;
3789 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003790
Lloyd Pique4dccc412018-01-22 17:21:36 -08003791 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003792 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003793 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3794 if (idx < 0) {
3795 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3796 return;
3797 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003798 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003799 }
3800
Dominik Laskowski281644e2018-04-19 15:47:35 -07003801 int32_t type = hw->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003802 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003803 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003804 getHwComposer().setPowerMode(type, mode);
Dominik Laskowski281644e2018-04-19 15:47:35 -07003805 if (hw->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003806 // FIXME: eventthread only knows about the main display right now
3807 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003808 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003809 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003810
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003811 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003812 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003813 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003814
3815 struct sched_param param = {0};
3816 param.sched_priority = 1;
3817 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3818 ALOGW("Couldn't set SCHED_FIFO on display on");
3819 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003820 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003821 // Turn off the display
3822 struct sched_param param = {0};
3823 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3824 ALOGW("Couldn't set SCHED_OTHER on display off");
3825 }
3826
Dominik Laskowski281644e2018-04-19 15:47:35 -07003827 if (hw->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003828 disableHardwareVsync(true); // also cancels any in-progress resync
3829
Mathias Agopiancde87a32012-09-13 14:09:01 -07003830 // FIXME: eventthread only knows about the main display right now
3831 mEventThread->onScreenReleased();
3832 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003833
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003834 getHwComposer().setPowerMode(type, mode);
3835 mVisibleRegionsDirty = true;
3836 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003837 } else if (mode == HWC_POWER_MODE_DOZE ||
3838 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003839 // Update display while dozing
3840 getHwComposer().setPowerMode(type, mode);
Dominik Laskowski281644e2018-04-19 15:47:35 -07003841 if (hw->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003842 // FIXME: eventthread only knows about the main display right now
3843 mEventThread->onScreenAcquired();
3844 resyncToHardwareVsync(true);
3845 }
3846 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3847 // Leave display going to doze
Dominik Laskowski281644e2018-04-19 15:47:35 -07003848 if (hw->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003849 disableHardwareVsync(true); // also cancels any in-progress resync
3850 // FIXME: eventthread only knows about the main display right now
3851 mEventThread->onScreenReleased();
3852 }
3853 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003854 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003855 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003856 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003857 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003858 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003859}
3860
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003861void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3862 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003863 SurfaceFlinger& mFlinger;
3864 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003865 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003866 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003867 MessageSetPowerMode(SurfaceFlinger& flinger,
3868 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3869 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003870 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003871 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003872 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003873 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003874 mMode, mDisplay.get());
Dominik Laskowski281644e2018-04-19 15:47:35 -07003875 } else if (hw->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003876 ALOGW("Attempt to set power mode = %d for virtual display",
3877 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003878 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003879 mFlinger.setPowerModeInternal(
3880 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003881 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003882 return true;
3883 }
3884 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003885 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003886 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003887}
3888
3889// ---------------------------------------------------------------------------
3890
Lloyd Pique755e3192018-01-31 16:46:15 -08003891status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3892 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003893 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003894
Mathias Agopianbd115332013-04-18 16:41:04 -07003895 IPCThreadState* ipc = IPCThreadState::self();
3896 const int pid = ipc->getCallingPid();
3897 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003898
Mathias Agopianbd115332013-04-18 16:41:04 -07003899 if ((uid != AID_SHELL) &&
3900 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003901 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003902 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003903 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003904 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003905 // (this would indicate SF is stuck, but we want to be able to
3906 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003907 status_t err = mStateLock.timedLock(s2ns(1));
3908 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003909 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003910 result.appendFormat(
3911 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3912 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003913 }
3914
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003915 bool dumpAll = true;
3916 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003917 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003918
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003919 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003920 if ((index < numArgs) &&
3921 (args[index] == String16("--list"))) {
3922 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003923 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003924 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003925 }
3926
3927 if ((index < numArgs) &&
3928 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003929 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003930 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003931 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003932 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003933
3934 if ((index < numArgs) &&
3935 (args[index] == String16("--latency-clear"))) {
3936 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003937 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003938 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003939 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003940
3941 if ((index < numArgs) &&
3942 (args[index] == String16("--dispsync"))) {
3943 index++;
3944 mPrimaryDispSync.dump(result);
3945 dumpAll = false;
3946 }
Dan Stozab90cf072015-03-05 11:05:59 -08003947
3948 if ((index < numArgs) &&
3949 (args[index] == String16("--static-screen"))) {
3950 index++;
3951 dumpStaticScreenStats(result);
3952 dumpAll = false;
3953 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003954
3955 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003956 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003957 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003958 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003959 dumpAll = false;
3960 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003961
3962 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3963 index++;
3964 dumpWideColorInfo(result);
3965 dumpAll = false;
3966 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003967
3968 if ((index < numArgs) &&
3969 (args[index] == String16("--enable-layer-stats"))) {
3970 index++;
3971 mLayerStats.enable();
3972 dumpAll = false;
3973 }
3974
3975 if ((index < numArgs) &&
3976 (args[index] == String16("--disable-layer-stats"))) {
3977 index++;
3978 mLayerStats.disable();
3979 dumpAll = false;
3980 }
3981
3982 if ((index < numArgs) &&
3983 (args[index] == String16("--clear-layer-stats"))) {
3984 index++;
3985 mLayerStats.clear();
3986 dumpAll = false;
3987 }
3988
3989 if ((index < numArgs) &&
3990 (args[index] == String16("--dump-layer-stats"))) {
3991 index++;
3992 mLayerStats.dump(result);
3993 dumpAll = false;
3994 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07003995
3996 if ((index < numArgs) &&
3997 (args[index] == String16("--display-identification"))) {
3998 index++;
3999 dumpDisplayIdentificationData(result);
4000 dumpAll = false;
4001 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004002
4003 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4004 index++;
4005 mTimeStats.parseArgs(asProto, args, index, result);
4006 dumpAll = false;
4007 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004008 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004009
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004010 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004011 if (asProto) {
4012 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4013 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4014 } else {
4015 dumpAllLocked(args, index, result);
4016 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004017 }
4018
Mathias Agopian9795c422009-08-26 16:36:26 -07004019 if (locked) {
4020 mStateLock.unlock();
4021 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004022 }
4023 write(fd, result.string(), result.size());
4024 return NO_ERROR;
4025}
4026
Dan Stozac7014012014-02-14 15:03:43 -08004027void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4028 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004029{
Robert Carr2047fae2016-11-28 14:09:09 -08004030 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004031 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004032 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004033}
4034
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004035void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004036 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004037{
4038 String8 name;
4039 if (index < args.size()) {
4040 name = String8(args[index]);
4041 index++;
4042 }
4043
David Sodman105b7dc2017-11-04 20:28:14 -07004044 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004045 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08004046 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004047
4048 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004049 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004050 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004051 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004052 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004053 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004054 }
Robert Carr2047fae2016-11-28 14:09:09 -08004055 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004056 }
4057}
4058
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004059void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004060 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004061{
4062 String8 name;
4063 if (index < args.size()) {
4064 name = String8(args[index]);
4065 index++;
4066 }
4067
Robert Carr2047fae2016-11-28 14:09:09 -08004068 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004069 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004070 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004071 }
Robert Carr2047fae2016-11-28 14:09:09 -08004072 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004073
Svetoslavd85084b2014-03-20 10:28:31 -07004074 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004075}
4076
Jamie Gennis6547ff42013-07-16 20:12:42 -07004077// This should only be called from the main thread. Otherwise it would need
4078// the lock and should use mCurrentState rather than mDrawingState.
4079void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004080 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004081 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004082 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004083
4084 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4085}
4086
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004087void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004088{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004089 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004090
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004091 if (isLayerTripleBufferingDisabled())
4092 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004093
4094 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004095 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004096 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004097 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004098 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4099 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004100 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004101}
4102
Dan Stozab90cf072015-03-05 11:05:59 -08004103void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4104{
4105 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004106 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4107 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004108 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004109 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004110 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4111 b + 1, bucketTimeSec, percent);
4112 }
David Sodman4a36e932017-11-07 14:29:47 -08004113 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004114 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004115 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004116 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004117 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004118}
4119
Dan Stozae77c7662016-05-13 11:37:28 -07004120void SurfaceFlinger::recordBufferingStats(const char* layerName,
4121 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004122 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4123 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004124 for (const auto& segment : history) {
4125 if (!segment.usedThirdBuffer) {
4126 stats.twoBufferTime += segment.totalTime;
4127 }
4128 if (segment.occupancyAverage < 1.0f) {
4129 stats.doubleBufferedTime += segment.totalTime;
4130 } else if (segment.occupancyAverage < 2.0f) {
4131 stats.tripleBufferedTime += segment.totalTime;
4132 }
4133 ++stats.numSegments;
4134 stats.totalTime += segment.totalTime;
4135 }
4136}
4137
Brian Andersond6927fb2016-07-23 23:37:30 -07004138void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4139 result.appendFormat("Layer frame timestamps:\n");
4140
4141 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4142 const size_t count = currentLayers.size();
4143 for (size_t i=0 ; i<count ; i++) {
4144 currentLayers[i]->dumpFrameEvents(result);
4145 }
4146}
4147
Dan Stozae77c7662016-05-13 11:37:28 -07004148void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4149 result.append("Buffering stats:\n");
4150 result.append(" [Layer name] <Active time> <Two buffer> "
4151 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004152 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004153 typedef std::tuple<std::string, float, float, float> BufferTuple;
4154 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004155 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004156 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004157 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004158 if (stats.numSegments == 0) {
4159 continue;
4160 }
4161 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4162 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4163 stats.totalTime;
4164 float doubleBufferRatio = static_cast<float>(
4165 stats.doubleBufferedTime) / stats.totalTime;
4166 float tripleBufferRatio = static_cast<float>(
4167 stats.tripleBufferedTime) / stats.totalTime;
4168 sorted.insert({activeTime, {name, twoBufferRatio,
4169 doubleBufferRatio, tripleBufferRatio}});
4170 }
4171 for (const auto& sortedPair : sorted) {
4172 float activeTime = sortedPair.first;
4173 const BufferTuple& values = sortedPair.second;
4174 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4175 std::get<0>(values).c_str(), activeTime,
4176 std::get<1>(values), std::get<2>(values),
4177 std::get<3>(values));
4178 }
4179 result.append("\n");
4180}
4181
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004182void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
4183 for (size_t d = 0; d < mDisplays.size(); d++) {
4184 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4185 const int32_t hwcId = displayDevice->getHwcDisplayId();
4186 const auto displayId = getHwComposer().getHwcDisplayId(hwcId);
4187 if (!displayId) {
4188 continue;
4189 }
4190
4191 result.appendFormat("Display %d: ", hwcId);
4192 uint8_t port;
4193 DisplayIdentificationData data;
4194 if (!getHwComposer().getDisplayIdentificationData(*displayId, &port, &data)) {
4195 result.append("no identification data\n");
4196 continue;
4197 }
4198
4199 if (!isEdid(data)) {
4200 result.append("unknown identification data: ");
4201 for (uint8_t byte : data) {
4202 result.appendFormat("%x ", byte);
4203 }
4204 result.append("\n");
4205 continue;
4206 }
4207
4208 const auto edid = parseEdid(data);
4209 if (!edid) {
4210 result.append("invalid EDID: ");
4211 for (uint8_t byte : data) {
4212 result.appendFormat("%x ", byte);
4213 }
4214 result.append("\n");
4215 continue;
4216 }
4217
4218 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4219 result.append(edid->displayName.data(), edid->displayName.length());
4220 result.append("\"\n");
4221 }
4222 result.append("\n");
4223}
4224
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004225void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4226 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004227 result.appendFormat("DisplayColorSetting: %d\n", mDisplayColorSetting);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004228
4229 // TODO: print out if wide-color mode is active or not
4230
4231 for (size_t d = 0; d < mDisplays.size(); d++) {
4232 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4233 int32_t hwcId = displayDevice->getHwcDisplayId();
4234 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4235 continue;
4236 }
4237
4238 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004239 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004240 for (auto&& mode : modes) {
4241 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4242 }
4243
Peiyong Lina52f0292018-03-14 17:26:31 -07004244 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004245 result.appendFormat(" Current color mode: %s (%d)\n",
4246 decodeColorMode(currentMode).c_str(), currentMode);
4247 }
4248 result.append("\n");
4249}
4250
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004251LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004252 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004253 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4254 const State& state = useDrawing ? mDrawingState : mCurrentState;
4255 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004256 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004257 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004258 });
4259
4260 return layersProto;
4261}
4262
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004263LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4264 LayersProto layersProto;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004265 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004266
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004267 SizeProto* resolution = layersProto.mutable_resolution();
4268 resolution->set_w(displayDevice->getWidth());
4269 resolution->set_h(displayDevice->getHeight());
4270
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004271 layersProto.set_color_mode(decodeColorMode(displayDevice->getActiveColorMode()));
4272 layersProto.set_color_transform(decodeColorTransform(displayDevice->getColorTransform()));
4273 layersProto.set_global_transform(
4274 static_cast<int32_t>(displayDevice->getOrientationTransform()));
4275
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004276 mDrawingState.traverseInZOrder([&](Layer* layer) {
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004277 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004278 LayerProto* layerProto = layersProto.add_layers();
4279 layer->writeToProto(layerProto, hwcId);
4280 }
4281 });
4282
4283 return layersProto;
4284}
4285
Mathias Agopian74d211a2013-04-22 16:55:35 +02004286void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4287 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004288{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004289 bool colorize = false;
4290 if (index < args.size()
4291 && (args[index] == String16("--color"))) {
4292 colorize = true;
4293 index++;
4294 }
4295
4296 Colorizer colorizer(colorize);
4297
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004298 // figure out if we're stuck somewhere
4299 const nsecs_t now = systemTime();
4300 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4301 const nsecs_t inTransaction(mDebugInTransaction);
4302 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4303 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4304
4305 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004306 * Dump library configuration.
4307 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004308
4309 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004310 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004311 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004312 appendSfConfigString(result);
4313 appendUiConfigString(result);
4314 appendGuiConfigString(result);
4315 result.append("\n");
4316
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004317 result.append("\nDisplay identification data:\n");
4318 dumpDisplayIdentificationData(result);
4319
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004320 result.append("\nWide-Color information:\n");
4321 dumpWideColorInfo(result);
4322
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004323 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004324 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004325 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004326 result.append(SyncFeatures::getInstance().toString());
4327 result.append("\n");
4328
David Sodman105b7dc2017-11-04 20:28:14 -07004329 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004330
Andy McFadden41d67d72014-04-25 16:58:34 -07004331 colorizer.bold(result);
4332 result.append("DispSync configuration: ");
4333 colorizer.reset(result);
Dan Stoza84d619e2018-03-28 17:07:36 -07004334 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, early sf phase %" PRId64
4335 " ns, present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4336 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, mVsyncModulator.getEarlyPhaseOffset(),
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004337 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004338 result.append("\n");
4339
Dan Stozab90cf072015-03-05 11:05:59 -08004340 // Dump static screen stats
4341 result.append("\n");
4342 dumpStaticScreenStats(result);
4343 result.append("\n");
4344
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004345 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4346
Dan Stozae77c7662016-05-13 11:37:28 -07004347 dumpBufferingStats(result);
4348
Andy McFadden4803b742012-09-24 19:07:20 -07004349 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004350 * Dump the visible layer list
4351 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004352 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004353 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004354 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4355 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004356 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004357
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004358 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004359 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004360 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004361 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004362
4363 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004364 * Dump Display state
4365 */
4366
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004367 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004368 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004369 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004370 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4371 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004372 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004373 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004374 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004375
4376 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004377 * Dump SurfaceFlinger global state
4378 */
4379
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004380 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004381 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004382 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004383
Mathias Agopian888c8222012-08-04 21:10:38 -07004384 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004385 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004386
David Sodmanbc815282017-11-05 18:57:52 -08004387 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004388
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004389 if (hw) {
4390 hw->undefinedRegion.dump(result, "undefinedRegion");
4391 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4392 hw->getOrientation(), hw->isDisplayOn());
4393 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004394 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004395 " last eglSwapBuffers() time: %f us\n"
4396 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004397 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004398 " refresh-rate : %f fps\n"
4399 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004400 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004401 " gpu_to_cpu_unsupported : %d\n"
4402 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004403 mLastSwapBufferTime/1000.0,
4404 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004405 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004406 1e9 / activeConfig->getVsyncPeriod(),
4407 activeConfig->getDpiX(),
4408 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004409 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004410
Mathias Agopian74d211a2013-04-22 16:55:35 +02004411 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004412 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004413
Mathias Agopian74d211a2013-04-22 16:55:35 +02004414 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004415 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004416
4417 /*
4418 * VSYNC state
4419 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004420 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004421 result.append("\n");
4422
4423 /*
4424 * HWC layer minidump
4425 */
4426 for (size_t d = 0; d < mDisplays.size(); d++) {
4427 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4428 int32_t hwcId = displayDevice->getHwcDisplayId();
4429 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4430 continue;
4431 }
4432
4433 result.appendFormat("Display %d HWC layers:\n", hwcId);
4434 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004435 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004436 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004437 });
Dan Stozae22aec72016-08-01 13:20:59 -07004438 result.append("\n");
4439 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004440
4441 /*
4442 * Dump HWComposer state
4443 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004444 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004445 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004446 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004447 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004448 result.appendFormat(" h/w composer %s\n",
4449 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004450 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004451
4452 /*
4453 * Dump gralloc state
4454 */
4455 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4456 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004457
4458 /*
4459 * Dump VrFlinger state if in use.
4460 */
4461 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4462 result.append("VrFlinger state:\n");
4463 result.append(mVrFlinger->Dump().c_str());
4464 result.append("\n");
4465 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004466}
4467
Mathias Agopian13127d82013-03-05 17:47:11 -08004468const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004469SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004470 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004471 wp<IBinder> dpy;
4472 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4473 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4474 dpy = mDisplays.keyAt(i);
4475 break;
4476 }
4477 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004478 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004479 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4480 // Just use the primary display so we have something to return
4481 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4482 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004483 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004484}
4485
Keun young Park63f165f2012-08-31 10:53:36 -07004486bool SurfaceFlinger::startDdmConnection()
4487{
4488 void* libddmconnection_dso =
4489 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4490 if (!libddmconnection_dso) {
4491 return false;
4492 }
4493 void (*DdmConnection_start)(const char* name);
4494 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004495 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004496 if (!DdmConnection_start) {
4497 dlclose(libddmconnection_dso);
4498 return false;
4499 }
4500 (*DdmConnection_start)(getServiceName());
4501 return true;
4502}
4503
Chia-I Wu28f320b2018-05-03 11:02:56 -07004504void SurfaceFlinger::updateColorMatrixLocked() {
4505 mat4 colorMatrix;
4506 if (mGlobalSaturationFactor != 1.0f) {
4507 // Rec.709 luma coefficients
4508 float3 luminance{0.213f, 0.715f, 0.072f};
4509 luminance *= 1.0f - mGlobalSaturationFactor;
4510 mat4 saturationMatrix = mat4(
4511 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4512 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4513 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4514 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4515 );
4516 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4517 } else {
4518 colorMatrix = mClientColorMatrix * mDaltonizer();
4519 }
4520
4521 if (mCurrentState.colorMatrix != colorMatrix) {
4522 mCurrentState.colorMatrix = colorMatrix;
4523 mCurrentState.colorMatrixChanged = true;
4524 setTransactionFlags(eTransactionNeeded);
4525 }
4526}
4527
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004528status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004529 switch (code) {
4530 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004531 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004532 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004533 case CLEAR_ANIMATION_FRAME_STATS:
4534 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004535 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004536 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004537 case ENABLE_VSYNC_INJECTIONS:
4538 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004539 {
4540 // codes that require permission check
4541 IPCThreadState* ipc = IPCThreadState::self();
4542 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004543 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004544 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004545 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004546 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004547 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004548 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004549 break;
4550 }
Robert Carr1db73f62016-12-21 12:58:51 -08004551 /*
4552 * Calling setTransactionState is safe, because you need to have been
4553 * granted a reference to Client* and Handle* to do anything with it.
4554 *
4555 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4556 */
4557 case SET_TRANSACTION_STATE:
4558 case CREATE_SCOPED_CONNECTION:
4559 {
4560 return OK;
4561 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004562 case CAPTURE_SCREEN:
4563 {
4564 // codes that require permission check
4565 IPCThreadState* ipc = IPCThreadState::self();
4566 const int pid = ipc->getCallingPid();
4567 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004568 if ((uid != AID_GRAPHICS) &&
4569 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004570 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004571 return PERMISSION_DENIED;
4572 }
4573 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004574 }
chaviwa76b2712017-09-20 12:02:26 -07004575 case CAPTURE_LAYERS: {
4576 IPCThreadState* ipc = IPCThreadState::self();
4577 const int pid = ipc->getCallingPid();
4578 const int uid = ipc->getCallingUid();
4579 if ((uid != AID_GRAPHICS) &&
4580 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4581 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4582 return PERMISSION_DENIED;
4583 }
4584 break;
4585 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004586 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004587 return OK;
4588}
4589
4590status_t SurfaceFlinger::onTransact(
4591 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4592{
4593 status_t credentialCheck = CheckTransactCodeCredentials(code);
4594 if (credentialCheck != OK) {
4595 return credentialCheck;
4596 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004597
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004598 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4599 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004600 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004601 IPCThreadState* ipc = IPCThreadState::self();
4602 const int uid = ipc->getCallingUid();
4603 if (CC_UNLIKELY(uid != AID_SYSTEM
4604 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004605 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004606 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004607 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004608 return PERMISSION_DENIED;
4609 }
4610 int n;
4611 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004612 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004613 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004614 return NO_ERROR;
4615 case 1002: // SHOW_UPDATES
4616 n = data.readInt32();
4617 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004618 invalidateHwcGeometry();
4619 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004620 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004621 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004622 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004623 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004624 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004625 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004626 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004627 setTransactionFlags(
4628 eTransactionNeeded|
4629 eDisplayTransactionNeeded|
4630 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004631 return NO_ERROR;
4632 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004633 case 1006:{ // send empty update
4634 signalRefresh();
4635 return NO_ERROR;
4636 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004637 case 1008: // toggle use of hw composer
4638 n = data.readInt32();
4639 mDebugDisableHWC = n ? 1 : 0;
4640 invalidateHwcGeometry();
4641 repaintEverything();
4642 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004643 case 1009: // toggle use of transform hint
4644 n = data.readInt32();
4645 mDebugDisableTransformHint = n ? 1 : 0;
4646 invalidateHwcGeometry();
4647 repaintEverything();
4648 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004649 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004650 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004651 reply->writeInt32(0);
4652 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004653 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004654 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004655 return NO_ERROR;
4656 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004657 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004658 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004659 return NO_ERROR;
4660 }
4661 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004662 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004663 // daltonize
4664 n = data.readInt32();
4665 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004666 case 1:
4667 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4668 break;
4669 case 2:
4670 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4671 break;
4672 case 3:
4673 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4674 break;
4675 default:
4676 mDaltonizer.setType(ColorBlindnessType::None);
4677 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004678 }
4679 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004680 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004681 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004682 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004683 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004684
4685 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004686 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004687 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004688 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004689 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004690 // apply a color matrix
4691 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004692 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004693 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004694 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004695 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004696 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004697 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004698 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004699 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004700 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004701 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004702
4703 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4704 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004705 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004706 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4707 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4708 }
4709
Chia-I Wu28f320b2018-05-03 11:02:56 -07004710 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004711 return NO_ERROR;
4712 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004713 // This is an experimental interface
4714 // Needs to be shifted to proper binder interface when we productize
4715 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004716 n = data.readInt32();
4717 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004718 return NO_ERROR;
4719 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004720 case 1017: {
4721 n = data.readInt32();
4722 mForceFullDamage = static_cast<bool>(n);
4723 return NO_ERROR;
4724 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004725 case 1018: { // Modify Choreographer's phase offset
4726 n = data.readInt32();
4727 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4728 return NO_ERROR;
4729 }
4730 case 1019: { // Modify SurfaceFlinger's phase offset
4731 n = data.readInt32();
4732 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4733 return NO_ERROR;
4734 }
Irvel468051e2016-06-13 16:44:44 -07004735 case 1020: { // Layer updates interceptor
4736 n = data.readInt32();
4737 if (n) {
4738 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004739 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004740 }
4741 else{
4742 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004743 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004744 }
4745 return NO_ERROR;
4746 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004747 case 1021: { // Disable HWC virtual displays
4748 n = data.readInt32();
4749 mUseHwcVirtualDisplays = !n;
4750 return NO_ERROR;
4751 }
Romain Guy0147a172017-06-01 13:53:56 -07004752 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004753 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004754 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004755
Chia-I Wu28f320b2018-05-03 11:02:56 -07004756 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004757 return NO_ERROR;
4758 }
Romain Guy54f154a2017-10-24 21:40:32 +01004759 case 1023: { // Set native mode
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004760 int32_t value = data.readInt32();
4761 if (value > 2) {
4762 return BAD_VALUE;
4763 }
4764 if (value == 2 && !mBuiltinDisplaySupportsEnhance) {
4765 return BAD_VALUE;
4766 }
Romain Guy54f154a2017-10-24 21:40:32 +01004767
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004768 mDisplayColorSetting = toDisplayColorSetting(value);
Romain Guy54f154a2017-10-24 21:40:32 +01004769 invalidateHwcGeometry();
4770 repaintEverything();
4771 return NO_ERROR;
4772 }
4773 case 1024: { // Is wide color gamut rendering/color management supported?
4774 reply->writeBool(hasWideColorDisplay);
4775 return NO_ERROR;
4776 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004777 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004778 n = data.readInt32();
4779 if (n) {
4780 ALOGV("LayerTracing enabled");
4781 mTracing.enable();
4782 doTracing("tracing.enable");
4783 reply->writeInt32(NO_ERROR);
4784 } else {
4785 ALOGV("LayerTracing disabled");
4786 status_t err = mTracing.disable();
4787 reply->writeInt32(err);
4788 }
4789 return NO_ERROR;
4790 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004791 case 1026: { // Get layer tracing status
4792 reply->writeBool(mTracing.isEnabled());
4793 return NO_ERROR;
4794 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004795 // Is a DisplayColorSetting supported?
4796 case 1027: {
4797 int32_t value = data.readInt32();
4798 switch (value) {
4799 case 0:
4800 reply->writeBool(hasWideColorDisplay);
4801 return NO_ERROR;
4802 case 1:
4803 reply->writeBool(true);
4804 return NO_ERROR;
4805 case 2:
4806 reply->writeBool(mBuiltinDisplaySupportsEnhance);
4807 return NO_ERROR;
4808 default:
4809 return BAD_VALUE;
4810 }
4811 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004812 }
4813 }
4814 return err;
4815}
4816
Steven Thomas6d8110b2017-08-31 18:24:21 -07004817void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004818 android_atomic_or(1, &mRepaintEverything);
4819 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004820}
4821
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004822// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4823class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004824public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004825 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4826 ~WindowDisconnector() {
4827 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004828 }
4829
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004830private:
4831 ANativeWindow* mWindow;
4832 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004833};
4834
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004835status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4836 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4837 int32_t minLayerZ, int32_t maxLayerZ,
4838 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004839 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004840 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004841
chaviwa76b2712017-09-20 12:02:26 -07004842 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4843
4844 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004845 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4846
chaviwa76b2712017-09-20 12:02:26 -07004847 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4848
4849 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4850 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004851 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004852}
4853
4854status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004855 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004856 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004857 ATRACE_CALL();
4858
4859 class LayerRenderArea : public RenderArea {
4860 public:
Robert Carr578038f2018-03-09 12:25:24 -08004861 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4862 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004863 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004864 mLayer(layer),
4865 mCrop(crop),
4866 mFlinger(flinger),
4867 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004868 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004869 Rect getBounds() const override {
4870 const Layer::State& layerState(mLayer->getDrawingState());
4871 return Rect(layerState.active.w, layerState.active.h);
4872 }
4873 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4874 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4875 bool isSecure() const override { return false; }
4876 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004877 Rect getSourceCrop() const override {
4878 if (mCrop.isEmpty()) {
4879 return getBounds();
4880 } else {
4881 return mCrop;
4882 }
4883 }
Robert Carr578038f2018-03-09 12:25:24 -08004884 class ReparentForDrawing {
4885 public:
4886 const sp<Layer>& oldParent;
4887 const sp<Layer>& newParent;
4888
4889 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4890 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004891 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004892 }
Robert Carr15eae092018-03-23 13:43:53 -07004893 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004894 };
4895
4896 void render(std::function<void()> drawLayers) override {
4897 if (!mChildrenOnly) {
4898 mTransform = mLayer->getTransform().inverse();
4899 drawLayers();
4900 } else {
4901 Rect bounds = getBounds();
4902 screenshotParentLayer =
4903 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4904 bounds.getWidth(), bounds.getHeight(), 0);
4905
4906 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4907 drawLayers();
4908 }
4909 }
chaviwa76b2712017-09-20 12:02:26 -07004910
chaviwa76b2712017-09-20 12:02:26 -07004911 private:
chaviw7206d492017-11-10 16:16:12 -08004912 const sp<Layer> mLayer;
4913 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004914
4915 // In the "childrenOnly" case we reparent the children to a screenshot
4916 // layer which has no properties set and which does not draw.
4917 sp<ContainerLayer> screenshotParentLayer;
4918 Transform mTransform;
4919
4920 SurfaceFlinger* mFlinger;
4921 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004922 };
4923
4924 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4925 auto parent = layerHandle->owner.promote();
4926
chaviw7206d492017-11-10 16:16:12 -08004927 if (parent == nullptr || parent->isPendingRemoval()) {
4928 ALOGE("captureLayers called with a removed parent");
4929 return NAME_NOT_FOUND;
4930 }
4931
Robert Carr578038f2018-03-09 12:25:24 -08004932 const int uid = IPCThreadState::self()->getCallingUid();
4933 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4934 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4935 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4936 return PERMISSION_DENIED;
4937 }
4938
chaviw7206d492017-11-10 16:16:12 -08004939 Rect crop(sourceCrop);
4940 if (sourceCrop.width() <= 0) {
4941 crop.left = 0;
4942 crop.right = parent->getCurrentState().active.w;
4943 }
4944
4945 if (sourceCrop.height() <= 0) {
4946 crop.top = 0;
4947 crop.bottom = parent->getCurrentState().active.h;
4948 }
4949
4950 int32_t reqWidth = crop.width() * frameScale;
4951 int32_t reqHeight = crop.height() * frameScale;
4952
Robert Carr578038f2018-03-09 12:25:24 -08004953 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004954
Robert Carr578038f2018-03-09 12:25:24 -08004955 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004956 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4957 if (!layer->isVisible()) {
4958 return;
Robert Carr578038f2018-03-09 12:25:24 -08004959 } else if (childrenOnly && layer == parent.get()) {
4960 return;
chaviwa76b2712017-09-20 12:02:26 -07004961 }
4962 visitor(layer);
4963 });
4964 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004965 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004966}
4967
4968status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4969 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004970 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004971 bool useIdentityTransform) {
4972 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004973
chaviwa76b2712017-09-20 12:02:26 -07004974 renderArea.updateDimensions();
4975
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004976 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4977 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4978 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4979 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004980
4981 // This mutex protects syncFd and captureResult for communication of the return values from the
4982 // main thread back to this Binder thread
4983 std::mutex captureMutex;
4984 std::condition_variable captureCondition;
4985 std::unique_lock<std::mutex> captureLock(captureMutex);
4986 int syncFd = -1;
4987 std::optional<status_t> captureResult;
4988
Robert Carr03480e22018-01-04 16:02:06 -08004989 const int uid = IPCThreadState::self()->getCallingUid();
4990 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4991
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004992 sp<LambdaMessage> message = new LambdaMessage([&]() {
4993 // If there is a refresh pending, bug out early and tell the binder thread to try again
4994 // after the refresh.
4995 if (mRefreshPending) {
4996 ATRACE_NAME("Skipping screenshot for now");
4997 std::unique_lock<std::mutex> captureLock(captureMutex);
4998 captureResult = std::make_optional<status_t>(EAGAIN);
4999 captureCondition.notify_one();
5000 return;
5001 }
5002
5003 status_t result = NO_ERROR;
5004 int fd = -1;
5005 {
5006 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08005007 renderArea.render([&]() {
5008 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5009 useIdentityTransform, forSystem, &fd);
5010 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005011 }
5012
5013 {
5014 std::unique_lock<std::mutex> captureLock(captureMutex);
5015 syncFd = fd;
5016 captureResult = std::make_optional<status_t>(result);
5017 captureCondition.notify_one();
5018 }
5019 });
5020
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005021 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005022 if (result == NO_ERROR) {
5023 captureCondition.wait(captureLock, [&]() { return captureResult; });
5024 while (*captureResult == EAGAIN) {
5025 captureResult.reset();
5026 result = postMessageAsync(message);
5027 if (result != NO_ERROR) {
5028 return result;
5029 }
5030 captureCondition.wait(captureLock, [&]() { return captureResult; });
5031 }
5032 result = *captureResult;
5033 }
5034
5035 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005036 sync_wait(syncFd, -1);
5037 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005038 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005039
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005040 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005041}
5042
chaviwa76b2712017-09-20 12:02:26 -07005043void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
5044 TraverseLayersFunction traverseLayers, bool yswap,
5045 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005046 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005047
Lloyd Pique144e1162017-12-20 16:44:52 -08005048 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005049
5050 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005051 const auto raWidth = renderArea.getWidth();
5052 const auto raHeight = renderArea.getHeight();
5053
5054 const auto reqWidth = renderArea.getReqWidth();
5055 const auto reqHeight = renderArea.getReqHeight();
5056 Rect sourceCrop = renderArea.getSourceCrop();
5057
5058 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5059 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005060
Dan Stozac1879002014-05-22 15:59:05 -07005061 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005062 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005063 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005064 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07005065 }
5066
5067 // ensure that sourceCrop is inside screen
5068 if (sourceCrop.left < 0) {
5069 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5070 }
chaviwa76b2712017-09-20 12:02:26 -07005071 if (sourceCrop.right > raWidth) {
5072 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005073 }
5074 if (sourceCrop.top < 0) {
5075 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5076 }
chaviwa76b2712017-09-20 12:02:26 -07005077 if (sourceCrop.bottom > raHeight) {
5078 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005079 }
5080
Chia-I Wu36574d92018-05-16 10:54:36 -07005081 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5082 engine.setOutputDataSpace(Dataspace::SRGB);
5083 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005084
Mathias Agopian180f10d2013-04-10 22:55:41 -07005085 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005086 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005087
5088 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005089 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
5090 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07005091 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005092
chaviw50da5042018-04-09 13:49:37 -07005093 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005094 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005095 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005096
chaviwa76b2712017-09-20 12:02:26 -07005097 traverseLayers([&](Layer* layer) {
5098 if (filtering) layer->setFiltering(true);
bohu21566132018-03-27 14:36:34 -07005099 layer->draw(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005100 if (filtering) layer->setFiltering(false);
5101 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005102}
5103
chaviwa76b2712017-09-20 12:02:26 -07005104status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5105 TraverseLayersFunction traverseLayers,
5106 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005107 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005108 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005109 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005110 ATRACE_CALL();
5111
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005112 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005113
5114 traverseLayers([&](Layer* layer) {
5115 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5116 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005117
Robert Carr03480e22018-01-04 16:02:06 -08005118 // We allow the system server to take screenshots of secure layers for
5119 // use in situations like the Screen-rotation animation and place
5120 // the impetus on WindowManager to not persist them.
5121 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005122 ALOGW("FB is protected: PERMISSION_DENIED");
5123 return PERMISSION_DENIED;
5124 }
5125
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005126 // this binds the given EGLImage as a framebuffer for the
5127 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005128 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005129 if (bufferBond.getStatus() != NO_ERROR) {
5130 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005131 return INVALID_OPERATION;
5132 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005133
Dan Stozaabcda352017-06-01 14:37:39 -07005134 // this will in fact render into our dequeued buffer
5135 // via an FBO, which means we didn't have to create
5136 // an EGLSurface and therefore we're not
5137 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005138 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005139
Dan Stozaabcda352017-06-01 14:37:39 -07005140 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005141 getRenderEngine().finish();
5142 *outSyncFd = -1;
5143
chaviwa76b2712017-09-20 12:02:26 -07005144 const auto reqWidth = renderArea.getReqWidth();
5145 const auto reqHeight = renderArea.getReqHeight();
5146
Dan Stozaabcda352017-06-01 14:37:39 -07005147 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5148 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005149 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005150 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005151 } else {
5152 base::unique_fd syncFd = getRenderEngine().flush();
5153 if (syncFd < 0) {
5154 getRenderEngine().finish();
5155 }
5156 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005157 }
5158
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005159 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005160}
5161
Mathias Agopiand5556842013-09-19 17:08:37 -07005162void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005163 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005164 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005165 for (size_t y = 0; y < h; y++) {
5166 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5167 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005168 if (p[x] != 0xFF000000) return;
5169 }
5170 }
chaviwa76b2712017-09-20 12:02:26 -07005171 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005172
Robert Carr2047fae2016-11-28 14:09:09 -08005173 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005174 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005175 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005176 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5177 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5178 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5179 static_cast<float>(state.color.a));
5180 i++;
5181 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005182 }
5183}
5184
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005185// ---------------------------------------------------------------------------
5186
Dan Stoza412903f2017-04-27 13:42:17 -07005187void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5188 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005189}
5190
Dan Stoza412903f2017-04-27 13:42:17 -07005191void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5192 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005193}
5194
chaviwa76b2712017-09-20 12:02:26 -07005195void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
5196 int32_t maxLayerZ,
5197 const LayerVector::Visitor& visitor) {
5198 // We loop through the first level of layers without traversing,
5199 // as we need to interpret min/max layer Z in the top level Z space.
5200 for (const auto& layer : mDrawingState.layersSortedByZ) {
5201 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5202 continue;
5203 }
5204 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005205 // relative layers are traversed in Layer::traverseInZOrder
5206 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005207 continue;
5208 }
5209 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005210 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5211 return;
5212 }
chaviwa76b2712017-09-20 12:02:26 -07005213 if (!layer->isVisible()) {
5214 return;
5215 }
5216 visitor(layer);
5217 });
5218 }
5219}
5220
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005221}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005222
Chia-I Wu30505fb2018-03-26 16:20:31 -07005223
Mathias Agopian3f844832013-08-07 21:24:32 -07005224#if defined(__gl_h_)
5225#error "don't include gl/gl.h in this file"
5226#endif
5227
5228#if defined(__gl2_h_)
5229#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005230#endif