blob: 1cf1f7ef4b11ff9022d1e2b3ccfe733b831e66f9 [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");
641 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(), *this, false,
642 "appEventThread");
643 mSfEventThreadSource =
644 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
645 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800646
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800647 mSFEventThread = std::make_unique<impl::EventThread>(mSfEventThreadSource.get(), *this, true,
648 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800649 mEventQueue->setEventThread(mSFEventThread.get());
Dan Stoza84d619e2018-03-28 17:07:36 -0700650 mVsyncModulator.setEventThread(mSFEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800651
Steven Thomasb02664d2017-07-26 18:48:28 -0700652 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800653 getBE().mRenderEngine =
654 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
655 hasWideColorDisplay
656 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
657 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800658 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700659
660 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
661 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800662 getBE().mHwc.reset(
663 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700664 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800665 // Process any initial hotplug and resulting display changes.
666 processDisplayHotplugEventsLocked();
667 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
668 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800669
Lloyd Piquefcd86612017-12-14 17:15:36 -0800670 // make the default display GLContext current so that we can create textures
671 // when creating Layers (which may happens before we render something)
672 getDefaultDisplayDeviceLocked()->makeCurrent();
673
Steven Thomas050b2c82017-03-06 11:45:16 -0800674 if (useVrFlinger) {
675 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700676 // This callback is called from the vr flinger dispatch thread. We
677 // need to call signalTransaction(), which requires holding
678 // mStateLock when we're not on the main thread. Acquiring
679 // mStateLock from the vr flinger dispatch thread might trigger a
680 // deadlock in surface flinger (see b/66916578), so post a message
681 // to be handled on the main thread instead.
682 sp<LambdaMessage> message = new LambdaMessage([=]() {
683 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
684 mVrFlingerRequestsDisplay = requestDisplay;
685 signalTransaction();
686 });
687 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800688 };
David Sodman105b7dc2017-11-04 20:28:14 -0700689 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
690 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800691 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800692 if (!mVrFlinger) {
693 ALOGE("Failed to start vrflinger");
694 }
695 }
696
Lloyd Pique379adc12018-01-22 17:31:47 -0800697 mEventControlThread = std::make_unique<impl::EventControlThread>(
698 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700699
Mathias Agopian92a979a2012-08-02 18:32:23 -0700700 // initialize our drawing state
701 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700702
Andy McFadden13a082e2012-08-24 10:16:42 -0700703 // set initial conditions (e.g. unblank default device)
704 initializeDisplays();
705
David Sodmanbc815282017-11-05 18:57:52 -0800706 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700707
Wei Wangf9b05ee2017-07-19 20:59:39 -0700708 // Inform native graphics APIs whether the present timestamp is supported:
709 if (getHwComposer().hasCapability(
710 HWC2::Capability::PresentFenceIsNotReliable)) {
711 mStartPropertySetThread = new StartPropertySetThread(false);
712 } else {
713 mStartPropertySetThread = new StartPropertySetThread(true);
714 }
715
716 if (mStartPropertySetThread->Start() != NO_ERROR) {
717 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800718 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800719
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800720 mLegacySrgbSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(HWC_DISPLAY_PRIMARY,
721 Dataspace::SRGB_LINEAR);
722
Dan Stoza9e56aa02015-11-02 13:00:03 -0800723 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700724}
725
Romain Guy11d63f42017-07-20 12:47:14 -0700726void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700727 Mutex::Autolock _l(mStateLock);
728
Romain Guy11d63f42017-07-20 12:47:14 -0700729 char value[PROPERTY_VALUE_MAX];
730
731 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800732 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700733 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800734 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100735
736 property_get("persist.sys.sf.native_mode", value, "0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800737 mDisplayColorSetting = toDisplayColorSetting(atoi(value));
738 ALOGV("Display Color Setting is set to %s.",
739 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Romain Guy11d63f42017-07-20 12:47:14 -0700740}
741
Mathias Agopiana67e4182012-06-19 17:26:12 -0700742void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800743 // Start boot animation service by setting a property mailbox
744 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700745 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800746 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700747 if (mStartPropertySetThread->join() != NO_ERROR) {
748 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800749 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700750}
751
Mathias Agopian875d8e12013-06-07 15:35:48 -0700752size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800753 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700754}
755
Mathias Agopian875d8e12013-06-07 15:35:48 -0700756size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800757 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700758}
759
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800760// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800761
Jamie Gennis582270d2011-08-17 18:19:00 -0700762bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800763 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800764 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800765 return authenticateSurfaceTextureLocked(bufferProducer);
766}
767
768bool SurfaceFlinger::authenticateSurfaceTextureLocked(
769 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800770 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800771 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800772}
773
Brian Anderson6b376712017-04-04 10:51:39 -0700774status_t SurfaceFlinger::getSupportedFrameTimestamps(
775 std::vector<FrameEvent>* outSupported) const {
776 *outSupported = {
777 FrameEvent::REQUESTED_PRESENT,
778 FrameEvent::ACQUIRE,
779 FrameEvent::LATCH,
780 FrameEvent::FIRST_REFRESH_START,
781 FrameEvent::LAST_REFRESH_START,
782 FrameEvent::GPU_COMPOSITION_DONE,
783 FrameEvent::DEQUEUE_READY,
784 FrameEvent::RELEASE,
785 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700786 ConditionalLock _l(mStateLock,
787 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700788 if (!getHwComposer().hasCapability(
789 HWC2::Capability::PresentFenceIsNotReliable)) {
790 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
791 }
792 return NO_ERROR;
793}
794
Dan Stoza7f7da322014-05-02 15:26:25 -0700795status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
796 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800797 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700798 return BAD_VALUE;
799 }
800
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500801 if (!display.get())
802 return NAME_NOT_FOUND;
803
Jesse Hall692c7232012-11-08 15:41:56 -0800804 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700805 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800806 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700807 type = i;
808 break;
809 }
810 }
811
812 if (type < 0) {
813 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700814 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700815
Mathias Agopian8b736f12012-08-13 17:54:26 -0700816 // TODO: Not sure if display density should handled by SF any longer
817 class Density {
818 static int getDensityFromProperty(char const* propName) {
819 char property[PROPERTY_VALUE_MAX];
820 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800821 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700822 density = atoi(property);
823 }
824 return density;
825 }
826 public:
827 static int getEmuDensity() {
828 return getDensityFromProperty("qemu.sf.lcd_density"); }
829 static int getBuildDensity() {
830 return getDensityFromProperty("ro.sf.lcd_density"); }
831 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700832
Dan Stoza7f7da322014-05-02 15:26:25 -0700833 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700834
Steven Thomas6d8110b2017-08-31 18:24:21 -0700835 ConditionalLock _l(mStateLock,
836 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800837 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700838 DisplayInfo info = DisplayInfo();
839
Dan Stoza9e56aa02015-11-02 13:00:03 -0800840 float xdpi = hwConfig->getDpiX();
841 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700842
843 if (type == DisplayDevice::DISPLAY_PRIMARY) {
844 // The density of the device is provided by a build property
845 float density = Density::getBuildDensity() / 160.0f;
846 if (density == 0) {
847 // the build doesn't provide a density -- this is wrong!
848 // use xdpi instead
849 ALOGE("ro.sf.lcd_density must be defined as a build property");
850 density = xdpi / 160.0f;
851 }
852 if (Density::getEmuDensity()) {
853 // if "qemu.sf.lcd_density" is specified, it overrides everything
854 xdpi = ydpi = density = Density::getEmuDensity();
855 density /= 160.0f;
856 }
857 info.density = density;
858
859 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700860 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800861 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700862 } else {
863 // TODO: where should this value come from?
864 static const int TV_DENSITY = 213;
865 info.density = TV_DENSITY / 160.0f;
866 info.orientation = 0;
867 }
868
Dan Stoza9e56aa02015-11-02 13:00:03 -0800869 info.w = hwConfig->getWidth();
870 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700871 info.xdpi = xdpi;
872 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800873 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900874 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800875
Andy McFadden91b2ca82014-06-13 14:04:23 -0700876 // This is how far in advance a buffer must be queued for
877 // presentation at a given time. If you want a buffer to appear
878 // on the screen at time N, you must submit the buffer before
879 // (N - presentationDeadline).
880 //
881 // Normally it's one full refresh period (to give SF a chance to
882 // latch the buffer), but this can be reduced by configuring a
883 // DispSync offset. Any additional delays introduced by the hardware
884 // composer or panel must be accounted for here.
885 //
886 // We add an additional 1ms to allow for processing time and
887 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800888 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800889 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700890
891 // All non-virtual displays are currently considered secure.
892 info.secure = true;
893
Michael Wright28f24d02016-07-12 13:30:53 -0700894 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700895 }
896
Dan Stoza7f7da322014-05-02 15:26:25 -0700897 return NO_ERROR;
898}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700899
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800900status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700901 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800902 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700903 return BAD_VALUE;
904 }
905
906 // FIXME for now we always return stats for the primary display
907 memset(stats, 0, sizeof(*stats));
908 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
909 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
910 return NO_ERROR;
911}
912
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700913int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800914 if (display == nullptr) {
915 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800916 return BAD_VALUE;
917 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700918
919 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800920 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700921 return device->getActiveConfig();
922 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700923
Dan Stoza24a42e92015-03-09 10:04:11 -0700924 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700925}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700926
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700927void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
928 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
929 this);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700930 int currentMode = hw->getActiveConfig();
931
932 if (mode == currentMode) {
933 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
934 return;
935 }
936
Dominik Laskowski281644e2018-04-19 15:47:35 -0700937 if (hw->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700938 ALOGW("Trying to set config for virtual display");
939 return;
940 }
941
942 hw->setActiveConfig(mode);
Dominik Laskowski281644e2018-04-19 15:47:35 -0700943 getHwComposer().setActiveConfig(hw->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700944}
945
946status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
947 class MessageSetActiveConfig: public MessageBase {
948 SurfaceFlinger& mFlinger;
949 sp<IBinder> mDisplay;
950 int mMode;
951 public:
952 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
953 int mode) :
954 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
955 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700956 Vector<DisplayInfo> configs;
957 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700958 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700959 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700960 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700961 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700962 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700963 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800964 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700965 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700966 mMode, mDisplay.get());
Dominik Laskowski281644e2018-04-19 15:47:35 -0700967 } else if (hw->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700968 ALOGW("Attempt to set active config = %d for virtual display",
969 mMode);
970 } else {
971 mFlinger.setActiveConfigInternal(hw, mMode);
972 }
973 return true;
974 }
975 };
976 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
977 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700978 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700979}
Michael Wright28f24d02016-07-12 13:30:53 -0700980status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -0700981 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700982 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
983 return BAD_VALUE;
984 }
985
986 if (!display.get()) {
987 return NAME_NOT_FOUND;
988 }
989
990 int32_t type = NAME_NOT_FOUND;
991 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
992 if (display == mBuiltinDisplays[i]) {
993 type = i;
994 break;
995 }
996 }
997
998 if (type < 0) {
999 return type;
1000 }
1001
Peiyong Lina52f0292018-03-14 17:26:31 -07001002 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001003 {
1004 ConditionalLock _l(mStateLock,
1005 std::this_thread::get_id() != mMainThreadId);
1006 modes = getHwComposer().getColorModes(type);
1007 }
Michael Wright28f24d02016-07-12 13:30:53 -07001008 outColorModes->clear();
1009 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1010
1011 return NO_ERROR;
1012}
1013
Peiyong Lina52f0292018-03-14 17:26:31 -07001014ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001015 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -07001016 if (device != nullptr) {
1017 return device->getActiveColorMode();
1018 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001019 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001020}
1021
1022void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001023 ColorMode mode, Dataspace dataSpace,
1024 RenderIntent renderIntent) {
Peiyong Lina52f0292018-03-14 17:26:31 -07001025 ColorMode currentMode = hw->getActiveColorMode();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001026 Dataspace currentDataSpace = hw->getCompositionDataSpace();
Peiyong Lin38e9a562018-04-10 16:24:20 -07001027 RenderIntent currentRenderIntent = hw->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001028
Peiyong Lin38e9a562018-04-10 16:24:20 -07001029 if (mode == currentMode && dataSpace == currentDataSpace &&
1030 renderIntent == currentRenderIntent) {
1031 return;
1032 }
1033
Dominik Laskowski281644e2018-04-19 15:47:35 -07001034 if (hw->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001035 ALOGW("Trying to set config for virtual display");
1036 return;
1037 }
1038
1039 hw->setActiveColorMode(mode);
1040 hw->setCompositionDataSpace(dataSpace);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001041 hw->setActiveRenderIntent(renderIntent);
Dominik Laskowski281644e2018-04-19 15:47:35 -07001042 getHwComposer().setActiveColorMode(hw->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001043
1044 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
1045 decodeColorMode(mode).c_str(), mode,
1046 decodeRenderIntent(renderIntent).c_str(), renderIntent,
1047 hw->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001048}
1049
1050
1051status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001052 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -07001053 class MessageSetActiveColorMode: public MessageBase {
1054 SurfaceFlinger& mFlinger;
1055 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -07001056 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001057 public:
1058 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -07001059 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -07001060 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1061 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -07001062 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001063 mFlinger.getDisplayColorModes(mDisplay, &modes);
1064 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -07001065 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001066 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1067 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001068 return true;
1069 }
1070 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1071 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001072 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1073 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Dominik Laskowski281644e2018-04-19 15:47:35 -07001074 } else if (hw->isVirtual()) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001075 ALOGW("Attempt to set active color mode %s %d for virtual display",
1076 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001077 } else {
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001078 mFlinger.setActiveColorModeInternal(hw, mMode, Dataspace::UNKNOWN,
1079 RenderIntent::COLORIMETRIC);
Michael Wright28f24d02016-07-12 13:30:53 -07001080 }
1081 return true;
1082 }
1083 };
1084 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1085 postMessageSync(msg);
1086 return NO_ERROR;
1087}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001088
Svetoslavd85084b2014-03-20 10:28:31 -07001089status_t SurfaceFlinger::clearAnimationFrameStats() {
1090 Mutex::Autolock _l(mStateLock);
1091 mAnimFrameTracker.clearStats();
1092 return NO_ERROR;
1093}
1094
1095status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1096 Mutex::Autolock _l(mStateLock);
1097 mAnimFrameTracker.getStats(outStats);
1098 return NO_ERROR;
1099}
1100
Dan Stozac4f471e2016-03-24 09:31:08 -07001101status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1102 HdrCapabilities* outCapabilities) const {
1103 Mutex::Autolock _l(mStateLock);
1104
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001105 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001106 if (displayDevice == nullptr) {
1107 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1108 return BAD_VALUE;
1109 }
1110
Peiyong Linfb069302018-04-25 14:34:31 -07001111 // At this point the DisplayDeivce should already be set up,
1112 // meaning the luminance information is already queried from
1113 // hardware composer and stored properly.
1114 const HdrCapabilities& capabilities = displayDevice->getHdrCapabilities();
1115 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1116 capabilities.getDesiredMaxLuminance(),
1117 capabilities.getDesiredMaxAverageLuminance(),
1118 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001119
1120 return NO_ERROR;
1121}
1122
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001123status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001124 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1125 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001126
Chia-I Wu90f669f2017-10-05 14:24:41 -07001127 if (mInjectVSyncs == enable) {
1128 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001129 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001130
1131 if (enable) {
1132 ALOGV("VSync Injections enabled");
1133 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001134 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique0fcde1b2017-12-20 16:50:21 -08001135 mInjectorEventThread =
1136 std::make_unique<impl::EventThread>(mVSyncInjector.get(), *this, false,
1137 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001138 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001139 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001140 } else {
1141 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001142 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001143 }
1144
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001145 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001146 });
1147 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001148 return NO_ERROR;
1149}
1150
1151status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001152 Mutex::Autolock _l(mStateLock);
1153
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001154 if (!mInjectVSyncs) {
1155 ALOGE("VSync Injections not enabled");
1156 return BAD_VALUE;
1157 }
1158 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1159 ALOGV("Injecting VSync inside SurfaceFlinger");
1160 mVSyncInjector->onInjectSyncEvent(when);
1161 }
1162 return NO_ERROR;
1163}
1164
Lloyd Pique755e3192018-01-31 16:46:15 -08001165status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1166 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001167 IPCThreadState* ipc = IPCThreadState::self();
1168 const int pid = ipc->getCallingPid();
1169 const int uid = ipc->getCallingUid();
1170 if ((uid != AID_SHELL) &&
1171 !PermissionCache::checkPermission(sDump, pid, uid)) {
1172 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1173 return PERMISSION_DENIED;
1174 }
1175
1176 // Try to acquire a lock for 1s, fail gracefully
1177 const status_t err = mStateLock.timedLock(s2ns(1));
1178 const bool locked = (err == NO_ERROR);
1179 if (!locked) {
1180 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1181 return TIMED_OUT;
1182 }
1183
1184 outLayers->clear();
1185 mCurrentState.traverseInZOrder([&](Layer* layer) {
1186 outLayers->push_back(layer->getLayerDebugInfo());
1187 });
1188
1189 mStateLock.unlock();
1190 return NO_ERROR;
1191}
1192
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001193// ----------------------------------------------------------------------------
1194
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001195sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1196 ISurfaceComposer::VsyncSource vsyncSource) {
1197 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1198 return mSFEventThread->createEventConnection();
1199 } else {
1200 return mEventThread->createEventConnection();
1201 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001202}
1203
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001204// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001205
1206void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001207 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001208}
1209
1210void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001211 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001212}
1213
1214void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001215 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001216}
1217
1218void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001219 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001220 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001221}
1222
1223status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001224 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001225 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001226}
1227
1228status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001229 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001230 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001231 if (res == NO_ERROR) {
1232 msg->wait();
1233 }
1234 return res;
1235}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001236
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001237void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001238 do {
1239 waitForEvent();
1240 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001241}
1242
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001243void SurfaceFlinger::enableHardwareVsync() {
1244 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001245 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001246 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001247 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1248 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001249 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001250 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001251}
1252
Jesse Hall948fe0c2013-10-14 12:56:09 -07001253void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001254 Mutex::Autolock _l(mHWVsyncLock);
1255
Jesse Hall948fe0c2013-10-14 12:56:09 -07001256 if (makeAvailable) {
1257 mHWVsyncAvailable = true;
1258 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001259 // Hardware vsync is not currently available, so abort the resync
1260 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001261 return;
1262 }
1263
David Sodman105b7dc2017-11-04 20:28:14 -07001264 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001265 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001266
1267 mPrimaryDispSync.reset();
1268 mPrimaryDispSync.setPeriod(period);
1269
1270 if (!mPrimaryHWVsyncEnabled) {
1271 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001272 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1273 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001274 mPrimaryHWVsyncEnabled = true;
1275 }
1276}
1277
Jesse Hall948fe0c2013-10-14 12:56:09 -07001278void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001279 Mutex::Autolock _l(mHWVsyncLock);
1280 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001281 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1282 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001283 mPrimaryDispSync.endResync();
1284 mPrimaryHWVsyncEnabled = false;
1285 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001286 if (makeUnavailable) {
1287 mHWVsyncAvailable = false;
1288 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001289}
1290
Tim Murray4a4e4a22016-04-19 16:29:23 +00001291void SurfaceFlinger::resyncWithRateLimit() {
1292 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001293
1294 // No explicit locking is needed here since EventThread holds a lock while calling this method
1295 static nsecs_t sLastResyncAttempted = 0;
1296 const nsecs_t now = systemTime();
1297 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001298 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001299 }
Dan Stoza57164302017-05-08 14:03:54 -07001300 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001301}
1302
Steven Thomasb02664d2017-07-26 18:48:28 -07001303void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1304 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001305 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001306 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001307 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001308 return;
1309 }
1310
1311 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001312 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001313 return;
1314 }
1315
Jamie Gennisd1700752013-10-14 12:22:52 -07001316 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001317
Jamie Gennisd1700752013-10-14 12:22:52 -07001318 { // Scope for the lock
1319 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001320 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001321 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001322 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001323 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001324
1325 if (needsHwVsync) {
1326 enableHardwareVsync();
1327 } else {
1328 disableHardwareVsync(false);
1329 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001330}
1331
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001332void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001333 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1334 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001335}
1336
Lloyd Pique715a2c12017-12-14 17:18:08 -08001337void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1338 HWC2::Connection connection) {
1339 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1340 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001341
Lloyd Piqueba04e622017-12-14 17:11:26 -08001342 // Ignore events that do not have the right sequenceId.
1343 if (sequenceId != getBE().mComposerSequenceId) {
1344 return;
1345 }
1346
Steven Thomasb02664d2017-07-26 18:48:28 -07001347 // Only lock if we're not on the main thread. This function is normally
1348 // called on a hwbinder thread, but for the primary display it's called on
1349 // the main thread with the state lock already held, so don't attempt to
1350 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001351 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001352
Lloyd Pique715a2c12017-12-14 17:18:08 -08001353 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001354
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001355 if (std::this_thread::get_id() == mMainThreadId) {
1356 // Process all pending hot plug events immediately if we are on the main thread.
1357 processDisplayHotplugEventsLocked();
1358 }
1359
Lloyd Piqueba04e622017-12-14 17:11:26 -08001360 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001361}
1362
Steven Thomasb02664d2017-07-26 18:48:28 -07001363void SurfaceFlinger::onRefreshReceived(int sequenceId,
1364 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001365 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001366 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001367 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001368 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001369 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001370}
1371
Dan Stoza9e56aa02015-11-02 13:00:03 -08001372void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001373 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001374 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001375 getHwComposer().setVsyncEnabled(disp,
1376 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001377}
1378
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001379// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001380void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001381 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001382 // Clear the drawing state so that the logic inside of
1383 // handleTransactionLocked will fire. It will determine the delta between
1384 // mCurrentState and mDrawingState and re-apply all changes when we make the
1385 // transition.
1386 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001387 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001388 mDisplays.clear();
1389}
1390
Steven Thomas050b2c82017-03-06 11:45:16 -08001391void SurfaceFlinger::updateVrFlinger() {
1392 if (!mVrFlinger)
1393 return;
1394 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001395 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001396 return;
1397 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001398
David Sodman105b7dc2017-11-04 20:28:14 -07001399 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001400 ALOGE("Vr flinger is only supported for remote hardware composer"
1401 " service connections. Ignoring request to transition to vr"
1402 " flinger.");
1403 mVrFlingerRequestsDisplay = false;
1404 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001405 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001406
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001407 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001408
Steven Thomasb02664d2017-07-26 18:48:28 -07001409 int currentDisplayPowerMode = getDisplayDeviceLocked(
1410 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001411
Steven Thomasb02664d2017-07-26 18:48:28 -07001412 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001413 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001414 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001415
Steven Thomasb02664d2017-07-26 18:48:28 -07001416 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001417 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001418 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1419 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001420 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001421
David Sodman105b7dc2017-11-04 20:28:14 -07001422 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1423 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001424
1425 if (vrFlingerRequestsDisplay) {
1426 mVrFlinger->GrantDisplayOwnership();
1427 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001428 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001429 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001430
1431 mVisibleRegionsDirty = true;
1432 invalidateHwcGeometry();
1433
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001434 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001435 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1436 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1437 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001438
Steven Thomasb02664d2017-07-26 18:48:28 -07001439 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001440 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001441 const nsecs_t period = activeConfig->getVsyncPeriod();
1442 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001443
Steven Thomasb02664d2017-07-26 18:48:28 -07001444 // Use phase of 0 since phase is not known.
1445 // Use latency of 0, which will snap to the ideal latency.
1446 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001447
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001448 android_atomic_or(1, &mRepaintEverything);
1449 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001450}
1451
Mathias Agopian4fec8732012-06-29 14:12:52 -07001452void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001453 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001454 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001455 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001456 bool frameMissed = !mHadClientComposition &&
1457 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001458 (mPreviousPresentFence->getSignalTime() ==
1459 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001460 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001461 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001462 mTimeStats.incrementMissedFrames();
1463 if (mPropagateBackpressure) {
1464 signalLayerUpdate();
1465 break;
1466 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001467 }
Dan Stoza50182882016-07-08 12:02:20 -07001468
Steven Thomas050b2c82017-03-06 11:45:16 -08001469 // Now that we're going to make it to the handleMessageTransaction()
1470 // call below it's safe to call updateVrFlinger(), which will
1471 // potentially trigger a display handoff.
1472 updateVrFlinger();
1473
Dan Stoza6b9454d2014-11-07 16:00:59 -08001474 bool refreshNeeded = handleMessageTransaction();
1475 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001476 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001477 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001478 // Signal a refresh if a transaction modified the window state,
1479 // a new buffer was latched, or if HWC has requested a full
1480 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001481 signalRefresh();
1482 }
1483 break;
1484 }
1485 case MessageQueue::REFRESH: {
1486 handleMessageRefresh();
1487 break;
1488 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001489 }
1490}
1491
Dan Stoza6b9454d2014-11-07 16:00:59 -08001492bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001493 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001494 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001495 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001496 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001497 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001498 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001499}
1500
Dan Stoza6b9454d2014-11-07 16:00:59 -08001501bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001502 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001503 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001504}
1505
1506void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001507 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001508
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001509 mRefreshPending = false;
1510
Chia-I Wu30505fb2018-03-26 16:20:31 -07001511 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001512
Chia-I Wu30505fb2018-03-26 16:20:31 -07001513 preComposition(refreshStartTime);
1514 rebuildLayerStacks();
1515 setUpHWComposer();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001516 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001517 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001518 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001519 doComposition();
Chia-I Wu30505fb2018-03-26 16:20:31 -07001520 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001521
David Sodman105b7dc2017-11-04 20:28:14 -07001522 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001523
1524 mHadClientComposition = false;
1525 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1526 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1527 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001528 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001529 }
Dan Stoza84d619e2018-03-28 17:07:36 -07001530 mVsyncModulator.setLastFrameUsedRenderEngine(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001531
Dan Stoza9e56aa02015-11-02 13:00:03 -08001532 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001533}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001534
Mathias Agopiancd60f992012-08-16 16:28:27 -07001535void SurfaceFlinger::doDebugFlashRegions()
1536{
1537 // is debugging enabled
1538 if (CC_LIKELY(!mDebugRegion))
1539 return;
1540
1541 const bool repaintEverything = mRepaintEverything;
1542 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1543 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001544 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001545 // transform the dirty region into this screen's coordinate space
1546 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1547 if (!dirtyRegion.isEmpty()) {
1548 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001549 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001550
1551 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001552 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001553 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001554 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1555
Mathias Agopianda27af92012-09-13 18:17:13 -07001556 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001557 }
1558 }
1559 }
1560
1561 postFramebuffer();
1562
1563 if (mDebugRegion > 1) {
1564 usleep(mDebugRegion * 1000);
1565 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001566
Dan Stoza9e56aa02015-11-02 13:00:03 -08001567 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001568 auto& displayDevice = mDisplays[displayId];
1569 if (!displayDevice->isDisplayOn()) {
1570 continue;
1571 }
1572
David Sodman105b7dc2017-11-04 20:28:14 -07001573 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1574 ALOGE_IF(result != NO_ERROR,
1575 "prepareFrame for display %zd failed:"
1576 " %d (%s)",
1577 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001578 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001579}
1580
Adrian Roos1e1a1282017-11-01 19:05:31 +01001581void SurfaceFlinger::doTracing(const char* where) {
1582 ATRACE_CALL();
1583 ATRACE_NAME(where);
1584 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001585 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001586 }
1587}
1588
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001589void SurfaceFlinger::logLayerStats() {
1590 ATRACE_CALL();
1591 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1592 int32_t hwcId = -1;
1593 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1594 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1595 if (displayDevice->isPrimary()) {
1596 hwcId = displayDevice->getHwcDisplayId();
1597 break;
1598 }
1599 }
1600 if (hwcId < 0) {
1601 ALOGE("LayerStats: Hmmm, no primary display?");
1602 return;
1603 }
1604 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1605 }
1606}
1607
Chia-I Wu30505fb2018-03-26 16:20:31 -07001608void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001609{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001610 ATRACE_CALL();
1611 ALOGV("preComposition");
1612
Mathias Agopiancd60f992012-08-16 16:28:27 -07001613 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001614 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001615 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001616 needExtraInvalidate = true;
1617 }
Robert Carr2047fae2016-11-28 14:09:09 -08001618 });
1619
Mathias Agopiancd60f992012-08-16 16:28:27 -07001620 if (needExtraInvalidate) {
1621 signalLayerUpdate();
1622 }
1623}
1624
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001625void SurfaceFlinger::updateCompositorTiming(
1626 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1627 std::shared_ptr<FenceTime>& presentFenceTime) {
1628 // Update queue of past composite+present times and determine the
1629 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001630 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001631 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001632 while (!getBE().mCompositePresentTimes.empty()) {
1633 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001634 // Cached values should have been updated before calling this method,
1635 // which helps avoid duplicate syscalls.
1636 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1637 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1638 break;
1639 }
1640 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001641 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001642 }
1643
1644 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001645 while (getBE().mCompositePresentTimes.size() > 16) {
1646 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001647 }
1648
Brian Andersond0010582017-03-07 13:20:31 -08001649 setCompositorTimingSnapped(
1650 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1651}
1652
1653void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1654 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001655 // Integer division and modulo round toward 0 not -inf, so we need to
1656 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001657 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001658 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1659 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1660
Brian Andersond0010582017-03-07 13:20:31 -08001661 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1662 if (idealLatency <= 0) {
1663 idealLatency = vsyncInterval;
1664 }
1665
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001666 // Snap the latency to a value that removes scheduling jitter from the
1667 // composition and present times, which often have >1ms of jitter.
1668 // Reducing jitter is important if an app attempts to extrapolate
1669 // something (such as user input) to an accurate diasplay time.
1670 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1671 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001672 nsecs_t bias = vsyncInterval / 2;
1673 int64_t extraVsyncs =
1674 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1675 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1676 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001677
David Sodman99974d22017-11-28 12:04:33 -08001678 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1679 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1680 getBE().mCompositorTiming.interval = vsyncInterval;
1681 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001682}
1683
Chia-I Wu30505fb2018-03-26 16:20:31 -07001684void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001685{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001686 ATRACE_CALL();
1687 ALOGV("postComposition");
1688
Brian Anderson3546a3f2016-07-14 11:51:14 -07001689 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001690 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001691 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001692 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001693 }
1694
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001695 // |mStateLock| not needed as we are on the main thread
1696 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001697
David Sodman73beded2017-11-15 11:56:06 -08001698 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001699 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001700 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001701 glCompositionDoneFenceTime =
1702 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001703 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001704 } else {
1705 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1706 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001707
David Sodman73beded2017-11-15 11:56:06 -08001708 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001709 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001710 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001711 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001712
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001713 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1714 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1715
Chia-I Wu30505fb2018-03-26 16:20:31 -07001716 // We use the refreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001717 // when we started doing work for this frame, but that should be okay
1718 // since updateCompositorTiming has snapping logic.
1719 updateCompositorTiming(
Chia-I Wu30505fb2018-03-26 16:20:31 -07001720 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001721 CompositorTiming compositorTiming;
1722 {
David Sodman99974d22017-11-28 12:04:33 -08001723 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1724 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001725 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001726
Robert Carr2047fae2016-11-28 14:09:09 -08001727 mDrawingState.traverseInZOrder([&](Layer* layer) {
1728 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001729 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001730 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001731 recordBufferingStats(layer->getName().string(),
1732 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001733 }
Robert Carr2047fae2016-11-28 14:09:09 -08001734 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001735
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001736 if (presentFenceTime->isValid()) {
1737 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001738 enableHardwareVsync();
1739 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001740 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001741 }
1742 }
1743
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001744 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001745 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001746 enableHardwareVsync();
1747 }
1748 }
1749
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001750 if (mAnimCompositionPending) {
1751 mAnimCompositionPending = false;
1752
Brian Anderson4e606e32017-03-16 15:34:57 -07001753 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001754 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001755 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001756 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001757 // The HWC doesn't support present fences, so use the refresh
1758 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001759 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001760 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001761 mAnimFrameTracker.setActualPresentTime(presentTime);
1762 }
1763 mAnimFrameTracker.advanceFrame();
1764 }
Dan Stozab90cf072015-03-05 11:05:59 -08001765
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001766 mTimeStats.incrementTotalFrames();
1767 if (mHadClientComposition) {
1768 mTimeStats.incrementClientCompositionFrames();
1769 }
1770
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001771 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1772 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001773 return;
1774 }
1775
1776 nsecs_t currentTime = systemTime();
1777 if (mHasPoweredOff) {
1778 mHasPoweredOff = false;
1779 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001780 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001781 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001782 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1783 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001784 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001785 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001786 }
David Sodman4a36e932017-11-07 14:29:47 -08001787 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001788 }
David Sodman4a36e932017-11-07 14:29:47 -08001789 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001790}
1791
1792void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001793 ATRACE_CALL();
1794 ALOGV("rebuildLayerStacks");
1795
Mathias Agopiancd60f992012-08-16 16:28:27 -07001796 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001797 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001798 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001799 mVisibleRegionsDirty = false;
1800 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001801
Jeff Sharkey76488112017-02-27 14:15:18 -07001802 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1803 Region opaqueRegion;
1804 Region dirtyRegion;
1805 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001806 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001807 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1808 const Transform& tr(displayDevice->getTransform());
1809 const Rect bounds(displayDevice->getBounds());
1810 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001811 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001812
Jeff Sharkey76488112017-02-27 14:15:18 -07001813 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001814 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001815 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1816 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001817 Region drawRegion(tr.transform(
1818 layer->visibleNonTransparentRegion));
1819 drawRegion.andSelf(bounds);
1820 if (!drawRegion.isEmpty()) {
1821 layersSortedByZ.add(layer);
1822 } else {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001823 // Clear out the HWC layer if this layer was
1824 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001825 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001826 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001827 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001828 } else {
1829 // WM changes displayDevice->layerStack upon sleep/awake.
1830 // Here we make sure we delete the HWC layers even if
1831 // WM changed their layer stack.
1832 hwcLayerDestroyed = layer->destroyHwcLayer(
1833 displayDevice->getHwcDisplayId());
Chia-I Wu83806892017-11-16 10:50:20 -08001834 }
1835
1836 // If a layer is not going to get a release fence because
1837 // it is invisible, but it is also going to release its
1838 // old buffer, add it to the list of layers needing
1839 // fences.
1840 if (hwcLayerDestroyed) {
1841 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1842 mLayersWithQueuedFrames.cend(), layer);
1843 if (found != mLayersWithQueuedFrames.cend()) {
1844 layersNeedingFences.add(layer);
1845 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001846 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001847 });
1848 }
1849 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001850 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001851 displayDevice->undefinedRegion.set(bounds);
1852 displayDevice->undefinedRegion.subtractSelf(
1853 tr.transform(opaqueRegion));
1854 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001855 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001856 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001857}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001858
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001859// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001860// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001861// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001862// - Dataspace::DISPLAY_P3
1863// - Dataspace::V0_SCRGB_LINEAR
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001864// The returned HDR data space is one of
1865// - Dataspace::UNKNOWN
1866// - Dataspace::BT2020_HLG
1867// - Dataspace::BT2020_PQ
1868Dataspace SurfaceFlinger::getBestDataspace(
1869 const sp<const DisplayDevice>& displayDevice, Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001870 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001871 *outHdrDataSpace = Dataspace::UNKNOWN;
1872
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001873 for (const auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wue1043322018-05-17 13:24:48 -07001874 switch (layer->getDrawingState().dataSpace) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001875 case Dataspace::V0_SCRGB:
1876 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001877 bestDataSpace = Dataspace::V0_SCRGB_LINEAR;
Peiyong Linf59a7192018-04-25 11:19:31 -07001878 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001879 case Dataspace::DISPLAY_P3:
Chia-I Wu7112a112018-05-07 15:27:06 -07001880 if (bestDataSpace == Dataspace::SRGB) {
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001881 bestDataSpace = Dataspace::DISPLAY_P3;
1882 }
1883 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001884 case Dataspace::BT2020_PQ:
1885 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001886 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001887 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001888 case Dataspace::BT2020_HLG:
1889 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001890 // When there's mixed PQ content and HLG content, we set the HDR
1891 // data space to be BT2020_PQ and convert HLG to PQ.
1892 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1893 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001894 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001895 break;
1896 default:
1897 break;
1898 }
Romain Guy54f154a2017-10-24 21:40:32 +01001899 }
1900
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001901 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001902}
1903
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001904// Pick the ColorMode / Dataspace for the display device.
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001905void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& displayDevice,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001906 ColorMode* outMode, Dataspace* outDataSpace,
1907 RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001908 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1909 *outMode = ColorMode::NATIVE;
1910 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001911 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001912 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001913 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001914
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001915 Dataspace hdrDataSpace;
1916 Dataspace bestDataSpace = getBestDataspace(displayDevice, &hdrDataSpace);
1917
1918 if (hdrDataSpace == Dataspace::BT2020_PQ) {
1919 // Hardware composer can handle BT2100 ColorMode only when
1920 // - colorimetrical tone mapping is supported, or
1921 // - Auto mode is turned on and enhanced tone mapping is supported.
1922 if (displayDevice->hasBT2100PQColorimetricSupport() ||
1923 (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
1924 displayDevice->hasBT2100PQEnhanceSupport())) {
1925 *outMode = ColorMode::BT2100_PQ;
1926 *outDataSpace = Dataspace::BT2020_PQ;
1927 } else if (displayDevice->hasHDR10Support()) {
1928 // Legacy HDR support. HDR layers are treated as UNKNOWN layers.
1929 hdrDataSpace = Dataspace::UNKNOWN;
1930 } else {
1931 // Simulate PQ through RenderEngine, pick DISPLAY_P3 color mode.
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001932 *outMode = ColorMode::DISPLAY_P3;
1933 *outDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001934 }
1935 } else if (hdrDataSpace == Dataspace::BT2020_HLG) {
1936 if (displayDevice->hasBT2100HLGColorimetricSupport() ||
1937 (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
1938 displayDevice->hasBT2100HLGEnhanceSupport())) {
1939 *outMode = ColorMode::BT2100_HLG;
1940 *outDataSpace = Dataspace::BT2020_HLG;
1941 } else if (displayDevice->hasHLGSupport()) {
1942 // Legacy HDR support. HDR layers are treated as UNKNOWN layers.
1943 hdrDataSpace = Dataspace::UNKNOWN;
1944 } else {
1945 // Simulate HLG through RenderEngine, pick DISPLAY_P3 color mode.
1946 *outMode = ColorMode::DISPLAY_P3;
1947 *outDataSpace = Dataspace::DISPLAY_P3;
1948 }
1949 }
1950
1951 // At this point, there's no HDR layer.
1952 if (hdrDataSpace == Dataspace::UNKNOWN) {
1953 switch (bestDataSpace) {
1954 case Dataspace::DISPLAY_P3:
1955 case Dataspace::V0_SCRGB_LINEAR:
1956 *outMode = ColorMode::DISPLAY_P3;
1957 *outDataSpace = Dataspace::DISPLAY_P3;
1958 break;
1959 default:
1960 *outMode = ColorMode::SRGB;
Chia-I Wu7112a112018-05-07 15:27:06 -07001961 *outDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001962 break;
1963 }
1964 }
1965 *outRenderIntent = pickRenderIntent(displayDevice, *outMode);
1966}
1967
1968RenderIntent SurfaceFlinger::pickRenderIntent(const sp<DisplayDevice>& displayDevice,
1969 ColorMode colorMode) const {
1970 // Native Mode means the display is not color managed, and whichever
1971 // render intent is picked doesn't matter, thus return
1972 // RenderIntent::COLORIMETRIC as default here.
1973 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1974 return RenderIntent::COLORIMETRIC;
1975 }
1976
1977 // In Auto Color Mode, we want to strech to panel color space, right now
1978 // only the built-in display supports it.
1979 if (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
1980 mBuiltinDisplaySupportsEnhance && displayDevice->isPrimary()) {
1981 switch (colorMode) {
1982 case ColorMode::DISPLAY_P3:
1983 case ColorMode::SRGB:
1984 return RenderIntent::ENHANCE;
1985 // In Auto Color Mode, BT2100_PQ and BT2100_HLG will only be picked
1986 // when TONE_MAP_ENHANCE or TONE_MAP_COLORIMETRIC is supported.
1987 // If TONE_MAP_ENHANCE is not supported, fall back to TONE_MAP_COLORIMETRIC.
1988 case ColorMode::BT2100_PQ:
1989 return displayDevice->hasBT2100PQEnhanceSupport() ?
1990 RenderIntent::TONE_MAP_ENHANCE : RenderIntent::TONE_MAP_COLORIMETRIC;
1991 case ColorMode::BT2100_HLG:
1992 return displayDevice->hasBT2100HLGEnhanceSupport() ?
1993 RenderIntent::TONE_MAP_ENHANCE : RenderIntent::TONE_MAP_COLORIMETRIC;
1994 // This statement shouldn't be reached, switch cases will always
1995 // cover all possible ColorMode returned by pickColorMode.
1996 default:
1997 return RenderIntent::COLORIMETRIC;
1998 }
1999 }
2000
2001 // Either enhance is not supported or we are in natural mode.
2002
2003 // Natural Mode means it's color managed and the color must be right,
2004 // thus we pick RenderIntent::COLORIMETRIC as render intent for non-HDR
2005 // content and pick RenderIntent::TONE_MAP_COLORIMETRIC for HDR content.
2006 switch (colorMode) {
2007 // In Natural Color Mode, BT2100_PQ and BT2100_HLG will only be picked
2008 // when TONE_MAP_COLORIMETRIC is supported.
2009 case ColorMode::BT2100_PQ:
2010 case ColorMode::BT2100_HLG:
2011 return RenderIntent::TONE_MAP_COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002012 default:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002013 return RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002014 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002015}
2016
Chia-I Wu30505fb2018-03-26 16:20:31 -07002017void SurfaceFlinger::setUpHWComposer() {
2018 ATRACE_CALL();
2019 ALOGV("setUpHWComposer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08002020
Jesse Hall028dc8f2013-08-20 16:35:32 -07002021 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Dan Stozac7a25ad2018-04-12 11:45:09 -07002022 bool dirty = !mDisplays[dpy]->getDirtyRegion(mRepaintEverything).isEmpty();
Jesse Hallb7a05492014-08-14 15:45:06 -07002023 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
2024 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
2025
2026 // If nothing has changed (!dirty), don't recompose.
2027 // If something changed, but we don't currently have any visible layers,
2028 // and didn't when we last did a composition, then skip it this time.
2029 // The second rule does two things:
2030 // - When all layers are removed from a display, we'll emit one black
2031 // frame, then nothing more until we get new layers.
2032 // - When a display is created with a private layer stack, we won't
2033 // emit any black frames until a layer is added to the layer stack.
2034 bool mustRecompose = dirty && !(empty && wasEmpty);
2035
Dominik Laskowski281644e2018-04-19 15:47:35 -07002036 ALOGV_IF(mDisplays[dpy]->isVirtual(),
Jesse Hallb7a05492014-08-14 15:45:06 -07002037 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
2038 mustRecompose ? "doing" : "skipping",
2039 dirty ? "+" : "-",
2040 empty ? "+" : "-",
2041 wasEmpty ? "+" : "-");
2042
Dan Stoza71433162014-02-04 16:22:36 -08002043 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07002044
2045 if (mustRecompose) {
2046 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
2047 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07002048 }
2049
Chia-I Wu30505fb2018-03-26 16:20:31 -07002050 // build the h/w work list
2051 if (CC_UNLIKELY(mGeometryInvalid)) {
2052 mGeometryInvalid = false;
2053 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2054 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
2055 const auto hwcId = displayDevice->getHwcDisplayId();
2056 if (hwcId >= 0) {
2057 const Vector<sp<Layer>>& currentLayers(
2058 displayDevice->getVisibleLayersSortedByZ());
2059 for (size_t i = 0; i < currentLayers.size(); i++) {
2060 const auto& layer = currentLayers[i];
2061 if (!layer->hasHwcLayer(hwcId)) {
2062 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
2063 layer->forceClientComposition(hwcId);
2064 continue;
2065 }
2066 }
2067
2068 layer->setGeometry(displayDevice, i);
2069 if (mDebugDisableHWC || mDebugRegion) {
2070 layer->forceClientComposition(hwcId);
2071 }
2072 }
2073 }
2074 }
2075 }
2076
Chia-I Wu30505fb2018-03-26 16:20:31 -07002077 // Set the per-frame data
2078 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2079 auto& displayDevice = mDisplays[displayId];
2080 const auto hwcId = displayDevice->getHwcDisplayId();
2081
2082 if (hwcId < 0) {
2083 continue;
2084 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07002085 if (mDrawingState.colorMatrixChanged) {
2086 displayDevice->setColorTransform(mDrawingState.colorMatrix);
2087 status_t result = getBE().mHwc->setColorTransform(hwcId, mDrawingState.colorMatrix);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002088 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
2089 "display %zd: %d", displayId, result);
2090 }
2091 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wue1043322018-05-17 13:24:48 -07002092 if ((layer->getDrawingState().dataSpace == Dataspace::BT2020_PQ ||
2093 layer->getDrawingState().dataSpace == Dataspace::BT2020_ITU_PQ) &&
Peiyong Lin62665892018-04-16 11:07:44 -07002094 !displayDevice->hasHDR10Support()) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07002095 layer->forceClientComposition(hwcId);
2096 }
Chia-I Wue1043322018-05-17 13:24:48 -07002097 if ((layer->getDrawingState().dataSpace == Dataspace::BT2020_HLG ||
2098 layer->getDrawingState().dataSpace == Dataspace::BT2020_ITU_HLG) &&
Peiyong Linf59a7192018-04-25 11:19:31 -07002099 !displayDevice->hasHLGSupport()) {
2100 layer->forceClientComposition(hwcId);
2101 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002102
2103 if (layer->getForceClientComposition(hwcId)) {
2104 ALOGV("[%s] Requesting Client composition", layer->getName().string());
2105 layer->setCompositionType(hwcId, HWC2::Composition::Client);
2106 continue;
2107 }
2108
2109 layer->setPerFrameData(displayDevice);
2110 }
2111
2112 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002113 ColorMode colorMode;
2114 Dataspace dataSpace;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002115 RenderIntent renderIntent;
2116 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
2117 setActiveColorModeInternal(displayDevice, colorMode, dataSpace, renderIntent);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002118 }
2119 }
2120
Chia-I Wu28f320b2018-05-03 11:02:56 -07002121 mDrawingState.colorMatrixChanged = false;
Chia-I Wu30505fb2018-03-26 16:20:31 -07002122
Dan Stoza9e56aa02015-11-02 13:00:03 -08002123 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002124 auto& displayDevice = mDisplays[displayId];
2125 if (!displayDevice->isDisplayOn()) {
2126 continue;
2127 }
2128
David Sodman105b7dc2017-11-04 20:28:14 -07002129 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002130 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2131 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002132 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002133}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002134
Mathias Agopiancd60f992012-08-16 16:28:27 -07002135void SurfaceFlinger::doComposition() {
2136 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002137 ALOGV("doComposition");
2138
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002139 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002140 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002141 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002142 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002143 // transform the dirty region into this screen's coordinate space
2144 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002145
2146 // repaint the framebuffer (if needed)
2147 doDisplayComposition(hw, dirtyRegion);
2148
Mathias Agopiancd60f992012-08-16 16:28:27 -07002149 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002150 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002151 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002152 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002153 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002154}
2155
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002156void SurfaceFlinger::postFramebuffer()
2157{
Mathias Agopian841cde52012-03-01 15:44:37 -08002158 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002159 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002160
Mathias Agopiana44b0412011-10-16 18:46:35 -07002161 const nsecs_t now = systemTime();
2162 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002163
Dan Stoza9e56aa02015-11-02 13:00:03 -08002164 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2165 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002166 if (!displayDevice->isDisplayOn()) {
2167 continue;
2168 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002169 const auto hwcId = displayDevice->getHwcDisplayId();
2170 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002171 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002172 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002173 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002174 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002175 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002176 // The layer buffer from the previous frame (if any) is released
2177 // by HWC only when the release fence from this frame (if any) is
2178 // signaled. Always get the release fence from HWC first.
2179 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002180 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002181
2182 // If the layer was client composited in the previous frame, we
2183 // need to merge with the previous client target acquire fence.
2184 // Since we do not track that, always merge with the current
2185 // client target acquire fence when it is available, even though
2186 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002187 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002188 releaseFence = Fence::merge("LayerRelease", releaseFence,
2189 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002190 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002191
David Sodmanb8af7922017-12-21 15:17:55 -08002192 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002193 }
Chia-I Wu83806892017-11-16 10:50:20 -08002194
2195 // We've got a list of layers needing fences, that are disjoint with
2196 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2197 // supply them with the present fence.
2198 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002199 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002200 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002201 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002202 }
2203 }
2204
Dan Stoza9e56aa02015-11-02 13:00:03 -08002205 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002206 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002207 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002208 }
2209
Mathias Agopiana44b0412011-10-16 18:46:35 -07002210 mLastSwapBufferTime = systemTime() - now;
2211 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002212
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002213 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002214 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2215 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2216 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2217 logFrameStats();
2218 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002219 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002220}
2221
Mathias Agopian87baae12012-07-31 12:38:26 -07002222void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002223{
Mathias Agopian841cde52012-03-01 15:44:37 -08002224 ATRACE_CALL();
2225
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002226 // here we keep a copy of the drawing state (that is the state that's
2227 // going to be overwritten by handleTransactionLocked()) outside of
2228 // mStateLock so that the side-effects of the State assignment
2229 // don't happen with mStateLock held (which can cause deadlocks).
2230 State drawingState(mDrawingState);
2231
Mathias Agopianca4d3602011-05-19 15:38:14 -07002232 Mutex::Autolock _l(mStateLock);
2233 const nsecs_t now = systemTime();
2234 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002235
Mathias Agopianca4d3602011-05-19 15:38:14 -07002236 // Here we're guaranteed that some transaction flags are set
2237 // so we can call handleTransactionLocked() unconditionally.
2238 // We call getTransactionFlags(), which will also clear the flags,
2239 // with mStateLock held to guarantee that mCurrentState won't change
2240 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002241
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002242 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002243 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002244 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002245
Mathias Agopianca4d3602011-05-19 15:38:14 -07002246 mLastTransactionTime = systemTime() - now;
2247 mDebugInTransaction = 0;
2248 invalidateHwcGeometry();
2249 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002250}
2251
Lloyd Pique715a2c12017-12-14 17:18:08 -08002252DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002253 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002254 // Figure out whether the event is for the primary display or an
2255 // external display by matching the Hwc display id against one for a
2256 // connected display. If we did not find a match, we then check what
2257 // displays are not already connected to determine the type. If we don't
2258 // have a connected primary display, we assume the new display is meant to
2259 // be the primary display, and then if we don't have an external display,
2260 // we assume it is that.
2261 const auto primaryDisplayId =
2262 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2263 const auto externalDisplayId =
2264 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2265 if (primaryDisplayId && primaryDisplayId == display) {
2266 return DisplayDevice::DISPLAY_PRIMARY;
2267 } else if (externalDisplayId && externalDisplayId == display) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002268 return DisplayDevice::DISPLAY_EXTERNAL;
Lloyd Pique715a2c12017-12-14 17:18:08 -08002269 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2270 return DisplayDevice::DISPLAY_PRIMARY;
2271 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2272 return DisplayDevice::DISPLAY_EXTERNAL;
2273 }
2274
2275 return DisplayDevice::DISPLAY_ID_INVALID;
2276}
2277
Lloyd Piqueba04e622017-12-14 17:11:26 -08002278void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2279 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002280 auto displayType = determineDisplayType(event.display, event.connection);
2281 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2282 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2283 continue;
2284 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002285
2286 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2287 ALOGE("External displays are not supported by the vr hardware composer.");
2288 continue;
2289 }
2290
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002291 const auto displayId =
2292 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
2293 if (displayId) {
2294 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.display, *displayId);
2295 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002296
2297 if (event.connection == HWC2::Connection::Connected) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002298 if (!mBuiltinDisplays[displayType].get()) {
2299 ALOGV("Creating built in display %d", displayType);
2300 mBuiltinDisplays[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002301 DisplayDeviceState info;
2302 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002303 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2304 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002305 info.isSecure = true; // All physical displays are currently considered secure.
Steven Thomaseb6d2052018-03-20 15:40:48 -07002306 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
2307 mInterceptor->saveDisplayCreation(info);
2308 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002309 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002310 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002311
Lloyd Piquefcd86612017-12-14 17:15:36 -08002312 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2313 if (idx >= 0) {
2314 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002315 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002316 mCurrentState.displays.removeItemsAt(idx);
2317 }
2318 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002319 }
2320
2321 processDisplayChangesLocked();
2322 }
2323
2324 mPendingHotplugEvents.clear();
2325}
2326
Lloyd Pique99d3da52018-01-22 17:48:03 -08002327sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2328 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2329 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002330 bool hasWideColorGamut = false;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002331 std::unordered_map<ColorMode, std::vector<RenderIntent>> hdrAndRenderIntents;
2332
Lloyd Pique99d3da52018-01-22 17:48:03 -08002333 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002334 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002335 for (ColorMode colorMode : modes) {
2336 switch (colorMode) {
2337 case ColorMode::DISPLAY_P3:
2338 case ColorMode::ADOBE_RGB:
2339 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002340 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002341 break;
2342 default:
2343 break;
2344 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002345
2346 std::vector<RenderIntent> renderIntents = getHwComposer().getRenderIntents(hwcId,
2347 colorMode);
2348 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2349 for (auto intent : renderIntents) {
2350 if (intent == RenderIntent::ENHANCE) {
2351 mBuiltinDisplaySupportsEnhance = true;
2352 break;
2353 }
2354 }
2355 }
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002356
2357 if (colorMode == ColorMode::BT2100_PQ || colorMode == ColorMode::BT2100_HLG) {
2358 hdrAndRenderIntents.emplace(colorMode, renderIntents);
2359 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002360 }
2361 }
2362
Peiyong Lin62665892018-04-16 11:07:44 -07002363 HdrCapabilities hdrCapabilities;
2364 getHwComposer().getHdrCapabilities(hwcId, &hdrCapabilities);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002365
2366 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2367 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2368
2369 /*
2370 * Create our display's surface
2371 */
2372 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2373 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002374 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002375 renderSurface->setNativeWindow(nativeWindow.get());
2376 const int displayWidth = renderSurface->queryWidth();
2377 const int displayHeight = renderSurface->queryHeight();
2378
2379 // Make sure that composition can never be stalled by a virtual display
2380 // consumer that isn't processing buffers fast enough. We have to do this
2381 // in two places:
2382 // * Here, in case the display is composed entirely by HWC.
2383 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2384 // window's swap interval in eglMakeCurrent, so they'll override the
2385 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002386 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002387 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2388 }
2389
2390 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002391 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002392
2393 sp<DisplayDevice> hw =
2394 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2395 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
Peiyong Lin0ac5f4e2018-04-19 22:06:34 -07002396 hasWideColorGamut, hdrCapabilities,
2397 getHwComposer().getSupportedPerFrameMetadata(hwcId),
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002398 hdrAndRenderIntents, initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002399
2400 if (maxFrameBufferAcquiredBuffers >= 3) {
2401 nativeWindowSurface->preallocateBuffers();
2402 }
2403
2404 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002405 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2406 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002407 defaultColorMode = ColorMode::SRGB;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002408 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002409 }
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002410 setActiveColorModeInternal(hw, defaultColorMode, defaultDataSpace,
2411 RenderIntent::COLORIMETRIC);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002412 hw->setLayerStack(state.layerStack);
2413 hw->setProjection(state.orientation, state.viewport, state.frame);
2414 hw->setDisplayName(state.displayName);
2415
2416 return hw;
2417}
2418
Lloyd Pique347200f2017-12-14 17:00:15 -08002419void SurfaceFlinger::processDisplayChangesLocked() {
2420 // here we take advantage of Vector's copy-on-write semantics to
2421 // improve performance by skipping the transaction entirely when
2422 // know that the lists are identical
2423 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2424 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2425 if (!curr.isIdenticalTo(draw)) {
2426 mVisibleRegionsDirty = true;
2427 const size_t cc = curr.size();
2428 size_t dc = draw.size();
2429
2430 // find the displays that were removed
2431 // (ie: in drawing state but not in current state)
2432 // also handle displays that changed
2433 // (ie: displays that are in both lists)
2434 for (size_t i = 0; i < dc;) {
2435 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2436 if (j < 0) {
2437 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002438 // Call makeCurrent() on the primary display so we can
2439 // be sure that nothing associated with this display
2440 // is current.
2441 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2442 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2443 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2444 if (hw != nullptr) hw->disconnect(getHwComposer());
2445 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2446 mEventThread->onHotplugReceived(draw[i].type, false);
2447 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002448 } else {
2449 // this display is in both lists. see if something changed.
2450 const DisplayDeviceState& state(curr[j]);
2451 const wp<IBinder>& display(curr.keyAt(j));
2452 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2453 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2454 if (state_binder != draw_binder) {
2455 // changing the surface is like destroying and
2456 // recreating the DisplayDevice, so we just remove it
2457 // from the drawing state, so that it get re-added
2458 // below.
2459 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2460 if (hw != nullptr) hw->disconnect(getHwComposer());
2461 mDisplays.removeItem(display);
2462 mDrawingState.displays.removeItemsAt(i);
2463 dc--;
2464 // at this point we must loop to the next item
2465 continue;
2466 }
2467
2468 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2469 if (disp != nullptr) {
2470 if (state.layerStack != draw[i].layerStack) {
2471 disp->setLayerStack(state.layerStack);
2472 }
2473 if ((state.orientation != draw[i].orientation) ||
2474 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2475 disp->setProjection(state.orientation, state.viewport, state.frame);
2476 }
2477 if (state.width != draw[i].width || state.height != draw[i].height) {
2478 disp->setDisplaySize(state.width, state.height);
2479 }
2480 }
2481 }
2482 ++i;
2483 }
2484
2485 // find displays that were added
2486 // (ie: in current state but not in drawing state)
2487 for (size_t i = 0; i < cc; i++) {
2488 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2489 const DisplayDeviceState& state(curr[i]);
2490
2491 sp<DisplaySurface> dispSurface;
2492 sp<IGraphicBufferProducer> producer;
2493 sp<IGraphicBufferProducer> bqProducer;
2494 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002495 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002496
2497 int32_t hwcId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002498 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002499 // Virtual displays without a surface are dormant:
2500 // they have external state (layer stack, projection,
2501 // etc.) but no internal state (i.e. a DisplayDevice).
2502 if (state.surface != nullptr) {
2503 // Allow VR composer to use virtual displays.
2504 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2505 int width = 0;
2506 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2507 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2508 int height = 0;
2509 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2510 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2511 int intFormat = 0;
2512 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2513 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002514 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002515
2516 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2517 }
2518
2519 // TODO: Plumb requested format back up to consumer
2520
2521 sp<VirtualDisplaySurface> vds =
2522 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2523 bqProducer, bqConsumer,
2524 state.displayName);
2525
2526 dispSurface = vds;
2527 producer = vds;
2528 }
2529 } else {
2530 ALOGE_IF(state.surface != nullptr,
2531 "adding a supported display, but rendering "
2532 "surface is provided (%p), ignoring it",
2533 state.surface.get());
2534
2535 hwcId = state.type;
2536 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2537 producer = bqProducer;
2538 }
2539
2540 const wp<IBinder>& display(curr.keyAt(i));
2541 if (dispSurface != nullptr) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002542 mDisplays.add(display,
2543 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2544 producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002545 if (!state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002546 mEventThread->onHotplugReceived(state.type, true);
2547 }
2548 }
2549 }
2550 }
2551 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002552
2553 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002554}
2555
Mathias Agopian87baae12012-07-31 12:38:26 -07002556void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002557{
Dan Stoza7dde5992015-05-22 09:51:44 -07002558 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002559 mCurrentState.traverseInZOrder([](Layer* layer) {
2560 layer->notifyAvailableFrames();
2561 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002562
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002563 /*
2564 * Traversal of the children
2565 * (perform the transaction for each of them if needed)
2566 */
2567
Mathias Agopian3559b072012-08-15 13:46:03 -07002568 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002569 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002570 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002571 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002572
2573 const uint32_t flags = layer->doTransaction(0);
2574 if (flags & Layer::eVisibleRegion)
2575 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002576 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002577 }
2578
2579 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002580 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002581 */
2582
Mathias Agopiane57f2922012-08-09 16:29:12 -07002583 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002584 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002585 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002586 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002587
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002588 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002589 // The transform hint might have changed for some layers
2590 // (either because a display has changed, or because a layer
2591 // as changed).
2592 //
2593 // Walk through all the layers in currentLayers,
2594 // and update their transform hint.
2595 //
2596 // If a layer is visible only on a single display, then that
2597 // display is used to calculate the hint, otherwise we use the
2598 // default display.
2599 //
2600 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2601 // the hint is set before we acquire a buffer from the surface texture.
2602 //
2603 // NOTE: layer transactions have taken place already, so we use their
2604 // drawing state. However, SurfaceFlinger's own transaction has not
2605 // happened yet, so we must use the current state layer list
2606 // (soon to become the drawing state list).
2607 //
2608 sp<const DisplayDevice> disp;
2609 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002610 bool first = true;
2611 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002612 // NOTE: we rely on the fact that layers are sorted by
2613 // layerStack first (so we don't have to traverse the list
2614 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002615 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002616 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002617 currentlayerStack = layerStack;
2618 // figure out if this layerstack is mirrored
2619 // (more than one display) if so, pick the default display,
2620 // if not, pick the only display it's on.
2621 disp.clear();
2622 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2623 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002624 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002625 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002626 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002627 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002628 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002629 break;
2630 }
2631 }
2632 }
2633 }
Chet Haase91d25932013-04-11 15:24:55 -07002634
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002635 if (disp == nullptr) {
2636 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2637 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002638
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002639 // could be null when this layer is using a layerStack
2640 // that is not visible on any display. Also can occur at
2641 // screen off/on times.
2642 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002643 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002644
2645 // disp can be null if there is no display available at all to get
2646 // the transform hint from.
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002647 if (disp != nullptr) {
2648 layer->updateTransformHint(disp);
2649 }
Robert Carr2047fae2016-11-28 14:09:09 -08002650
2651 first = false;
2652 });
Mathias Agopian84300952012-11-21 16:02:13 -08002653 }
2654
2655
Mathias Agopian3559b072012-08-15 13:46:03 -07002656 /*
2657 * Perform our own transaction if needed
2658 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002659
2660 if (mLayersAdded) {
2661 mLayersAdded = false;
2662 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002663 mVisibleRegionsDirty = true;
2664 }
2665
2666 // some layers might have been removed, so
2667 // we need to update the regions they're exposing.
2668 if (mLayersRemoved) {
2669 mLayersRemoved = false;
2670 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002671 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002672 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002673 // this layer is not visible anymore
2674 // TODO: we could traverse the tree from front to back and
2675 // compute the actual visible region
2676 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002677 Region visibleReg;
2678 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002679 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002680 }
Robert Carr2047fae2016-11-28 14:09:09 -08002681 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002682 }
2683
2684 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002685
2686 updateCursorAsync();
2687}
2688
2689void SurfaceFlinger::updateCursorAsync()
2690{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002691 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2692 auto& displayDevice = mDisplays[displayId];
2693 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002694 continue;
2695 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002696
2697 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2698 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002699 }
2700 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002701}
2702
2703void SurfaceFlinger::commitTransaction()
2704{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002705 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002706 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002707 for (const auto& l : mLayersPendingRemoval) {
2708 recordBufferingStats(l->getName().string(),
2709 l->getOccupancyHistory(true));
2710 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002711 }
2712 mLayersPendingRemoval.clear();
2713 }
2714
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002715 // If this transaction is part of a window animation then the next frame
2716 // we composite should be considered an animation as well.
2717 mAnimCompositionPending = mAnimTransactionPending;
2718
Mathias Agopian4fec8732012-06-29 14:12:52 -07002719 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002720 // clear the "changed" flags in current state
2721 mCurrentState.colorMatrixChanged = false;
2722
Robert Carr1f0a16a2016-10-24 16:27:39 -07002723 mDrawingState.traverseInZOrder([](Layer* layer) {
2724 layer->commitChildList();
2725 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002726 mTransactionPending = false;
2727 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002728 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002729}
2730
Chia-I Wuab0c3192017-08-01 11:29:00 -07002731void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002732 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002733{
Mathias Agopian841cde52012-03-01 15:44:37 -08002734 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002735 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002736
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002737 Region aboveOpaqueLayers;
2738 Region aboveCoveredLayers;
2739 Region dirty;
2740
Mathias Agopian87baae12012-07-31 12:38:26 -07002741 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002742
Robert Carr2047fae2016-11-28 14:09:09 -08002743 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002744 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002745 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002746
Jesse Hall01e29052013-02-19 16:13:35 -08002747 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002748 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002749 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002750
Mathias Agopianab028732010-03-16 16:41:46 -07002751 /*
2752 * opaqueRegion: area of a surface that is fully opaque.
2753 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002754 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002755
2756 /*
2757 * visibleRegion: area of a surface that is visible on screen
2758 * and not fully transparent. This is essentially the layer's
2759 * footprint minus the opaque regions above it.
2760 * Areas covered by a translucent surface are considered visible.
2761 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002762 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002763
2764 /*
2765 * coveredRegion: area of a surface that is covered by all
2766 * visible regions above it (which includes the translucent areas).
2767 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002768 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002769
Jesse Halla8026d22012-09-25 13:25:04 -07002770 /*
2771 * transparentRegion: area of a surface that is hinted to be completely
2772 * transparent. This is only used to tell when the layer has no visible
2773 * non-transparent regions and can be removed from the layer list. It
2774 * does not affect the visibleRegion of this layer or any layers
2775 * beneath it. The hint may not be correct if apps don't respect the
2776 * SurfaceView restrictions (which, sadly, some don't).
2777 */
2778 Region transparentRegion;
2779
Mathias Agopianab028732010-03-16 16:41:46 -07002780
2781 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002782 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002783 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002784 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002785 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002786 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002787 if (!visibleRegion.isEmpty()) {
2788 // Remove the transparent area from the visible region
2789 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002790 if (tr.preserveRects()) {
2791 // transform the transparent region
2792 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002793 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002794 // transformation too complex, can't do the
2795 // transparent region optimization.
2796 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002797 }
Mathias Agopianab028732010-03-16 16:41:46 -07002798 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002799
Mathias Agopianab028732010-03-16 16:41:46 -07002800 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002801 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002802 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002803 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2804 // the opaque region is the layer's footprint
2805 opaqueRegion = visibleRegion;
2806 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002807 }
2808 }
2809
Robert Carre5f4f692018-01-12 13:12:28 -08002810 if (visibleRegion.isEmpty()) {
2811 layer->clearVisibilityRegions();
2812 return;
2813 }
2814
Mathias Agopianab028732010-03-16 16:41:46 -07002815 // Clip the covered region to the visible region
2816 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2817
2818 // Update aboveCoveredLayers for next (lower) layer
2819 aboveCoveredLayers.orSelf(visibleRegion);
2820
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002821 // subtract the opaque region covered by the layers above us
2822 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002823
2824 // compute this layer's dirty region
2825 if (layer->contentDirty) {
2826 // we need to invalidate the whole region
2827 dirty = visibleRegion;
2828 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002829 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002830 layer->contentDirty = false;
2831 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002832 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002833 * the exposed region consists of two components:
2834 * 1) what's VISIBLE now and was COVERED before
2835 * 2) what's EXPOSED now less what was EXPOSED before
2836 *
2837 * note that (1) is conservative, we start with the whole
2838 * visible region but only keep what used to be covered by
2839 * something -- which mean it may have been exposed.
2840 *
2841 * (2) handles areas that were not covered by anything but got
2842 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002843 */
Mathias Agopianab028732010-03-16 16:41:46 -07002844 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002845 const Region oldVisibleRegion = layer->visibleRegion;
2846 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002847 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2848 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002849 }
2850 dirty.subtractSelf(aboveOpaqueLayers);
2851
2852 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002853 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002854
Mathias Agopianab028732010-03-16 16:41:46 -07002855 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002856 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002857
Jesse Halla8026d22012-09-25 13:25:04 -07002858 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002859 layer->setVisibleRegion(visibleRegion);
2860 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002861 layer->setVisibleNonTransparentRegion(
2862 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002863 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002864
Mathias Agopian87baae12012-07-31 12:38:26 -07002865 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002866}
2867
Chia-I Wuab0c3192017-08-01 11:29:00 -07002868void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002869 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002870 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002871 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002872 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002873 }
2874 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002875}
2876
Dan Stoza6b9454d2014-11-07 16:00:59 -08002877bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002878{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002879 ALOGV("handlePageFlip");
2880
Brian Andersond6927fb2016-07-23 23:37:30 -07002881 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002882
Mathias Agopian4fec8732012-06-29 14:12:52 -07002883 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002884 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002885 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002886
2887 // Store the set of layers that need updates. This set must not change as
2888 // buffers are being latched, as this could result in a deadlock.
2889 // Example: Two producers share the same command stream and:
2890 // 1.) Layer 0 is latched
2891 // 2.) Layer 0 gets a new frame
2892 // 2.) Layer 1 gets a new frame
2893 // 3.) Layer 1 is latched.
2894 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2895 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002896 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002897 if (layer->hasQueuedFrame()) {
2898 frameQueued = true;
2899 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002900 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002901 } else {
2902 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002903 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002904 } else {
2905 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002906 }
Robert Carr2047fae2016-11-28 14:09:09 -08002907 });
2908
Dan Stoza9e56aa02015-11-02 13:00:03 -08002909 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002910 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002911 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002912 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002913 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002914 newDataLatched = true;
2915 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002916 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002917
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002918 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002919
2920 // If we will need to wake up at some time in the future to deal with a
2921 // queued frame that shouldn't be displayed during this vsync period, wake
2922 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002923 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002924 signalLayerUpdate();
2925 }
2926
2927 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002928 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002929}
2930
Mathias Agopianad456f92011-01-13 17:53:01 -08002931void SurfaceFlinger::invalidateHwcGeometry()
2932{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002933 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002934}
2935
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002936
Fabien Sanglard830b8472016-11-30 16:35:58 -08002937void SurfaceFlinger::doDisplayComposition(
2938 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002939 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002940{
Dan Stoza71433162014-02-04 16:22:36 -08002941 // We only need to actually compose the display if:
2942 // 1) It is being handled by hardware composer, which may need this to
2943 // keep its virtual display state machine in sync, or
2944 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002945 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002946 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002947 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002948 return;
2949 }
2950
Dan Stoza9e56aa02015-11-02 13:00:03 -08002951 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002952 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002953
2954 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002955 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002956}
2957
Chia-I Wub02087d2017-11-09 10:19:54 -08002958bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002959{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002960 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002961
Chia-I Wub02087d2017-11-09 10:19:54 -08002962 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002963 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002964 const auto hwcId = displayDevice->getHwcDisplayId();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002965 const bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002966 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002967
Chia-I Wu8e50e692018-05-04 10:12:37 -07002968 bool applyColorMatrix = false;
Peiyong Lin00f9c022018-05-09 15:35:33 -07002969 bool needsLegacyColorMatrix = false;
2970 bool legacyColorMatrixApplied = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002971
Dan Stoza9e56aa02015-11-02 13:00:03 -08002972 if (hasClientComposition) {
2973 ALOGV("hasClientComposition");
2974
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002975 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002976 if (displayDevice->hasWideColorGamut()) {
2977 outputDataspace = displayDevice->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002978 }
2979 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002980 getBE().mRenderEngine->setDisplayMaxLuminance(
2981 displayDevice->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002982
Chia-I Wu8e50e692018-05-04 10:12:37 -07002983 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
2984 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2985 HWC2::Capability::SkipClientColorTransform);
2986
2987 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2988 if (applyColorMatrix) {
Peiyong Lin00f9c022018-05-09 15:35:33 -07002989 getRenderEngine().setupColorTransform(mDrawingState.colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002990 }
2991
Peiyong Lin00f9c022018-05-09 15:35:33 -07002992 needsLegacyColorMatrix = (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002993 outputDataspace != Dataspace::UNKNOWN &&
2994 outputDataspace != Dataspace::SRGB);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002995
Chia-I Wu7f402902017-11-09 12:51:10 -08002996 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002997 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskibf170d92018-04-19 15:08:05 -07002998 displayDevice->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08002999 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003000
3001 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08003002 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07003003 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
3004 }
3005 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003006 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003007
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003008 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003009 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003010 // when using overlays, we assume a fully transparent framebuffer
3011 // NOTE: we could reduce how much we need to clear, for instance
3012 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003013 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003014 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003015 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003016 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003017 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003018 // we're left with the letterbox region
3019 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08003020 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07003021
3022 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08003023 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07003024
Mathias Agopianb9494d52012-04-18 02:28:45 -07003025 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003026 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003027 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08003028 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003029 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003030 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003031
Dominik Laskowski281644e2018-04-19 15:47:35 -07003032 if (!displayDevice->isPrimary()) {
Mathias Agopian766dc492012-10-30 18:08:06 -07003033 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07003034 // scissor on the main display. It should never be needed
3035 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08003036 const Rect& bounds(displayDevice->getBounds());
3037 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003038 if (scissor != bounds) {
3039 // scissor doesn't match the screen's dimensions, so we
3040 // need to clear everything outside of it and enable
3041 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003042
Mathias Agopianf45c5102012-10-24 16:29:17 -07003043 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08003044 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08003045 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07003046 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003047 }
3048 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003049 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003050
Mathias Agopian85d751c2012-08-29 16:59:24 -07003051 /*
3052 * and then, render the layers targeted at the framebuffer
3053 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003054
Dan Stoza9e56aa02015-11-02 13:00:03 -08003055 ALOGV("Rendering client layers");
3056 const Transform& displayTransform = displayDevice->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003057 bool firstLayer = true;
3058 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
3059 const Region clip(bounds.intersect(
3060 displayTransform.transform(layer->visibleRegion)));
3061 ALOGV("Layer: %s", layer->getName().string());
3062 ALOGV(" Composition type: %s",
3063 to_string(layer->getCompositionType(hwcId)).c_str());
3064 if (!clip.isEmpty()) {
3065 switch (layer->getCompositionType(hwcId)) {
3066 case HWC2::Composition::Cursor:
3067 case HWC2::Composition::Device:
3068 case HWC2::Composition::Sideband:
3069 case HWC2::Composition::SolidColor: {
3070 const Layer::State& state(layer->getDrawingState());
3071 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
3072 layer->isOpaque(state) && (state.color.a == 1.0f)
3073 && hasClientComposition) {
3074 // never clear the very first layer since we're
3075 // guaranteed the FB is already cleared
3076 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003077 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003078 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003079 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003080 case HWC2::Composition::Client: {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003081 // switch color matrices lazily
Peiyong Lin00f9c022018-05-09 15:35:33 -07003082 if (layer->isLegacyDataSpace() && needsLegacyColorMatrix) {
3083 if (!legacyColorMatrixApplied) {
3084 getRenderEngine().setSaturationMatrix(mLegacySrgbSaturationMatrix);
3085 legacyColorMatrixApplied = true;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003086 }
Peiyong Lin00f9c022018-05-09 15:35:33 -07003087 } else if (legacyColorMatrixApplied) {
3088 getRenderEngine().setSaturationMatrix(mat4());
3089 legacyColorMatrixApplied = false;
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003090 }
Chia-I Wu8e50e692018-05-04 10:12:37 -07003091
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003092 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003093 break;
3094 }
3095 default:
3096 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003097 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003098 } else {
3099 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003100 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003101 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003102 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003103
Peiyong Lin00f9c022018-05-09 15:35:33 -07003104 if (applyColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003105 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003106 }
Peiyong Lin00f9c022018-05-09 15:35:33 -07003107 if (needsLegacyColorMatrix && legacyColorMatrixApplied) {
3108 getRenderEngine().setSaturationMatrix(mat4());
3109 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003110
Mathias Agopianf45c5102012-10-24 16:29:17 -07003111 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003112 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003113 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003114}
3115
Fabien Sanglard830b8472016-11-30 16:35:58 -08003116void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
3117 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003118 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003119 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003120}
3121
Dan Stoza7d89d062015-04-30 13:29:25 -07003122status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003123 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003124 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003125 const sp<Layer>& lbc,
3126 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003127{
Dan Stoza7d89d062015-04-30 13:29:25 -07003128 // add this layer to the current state list
3129 {
3130 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003131 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003132 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3133 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003134 return NO_MEMORY;
3135 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003136 if (parent == nullptr) {
3137 mCurrentState.layersSortedByZ.add(lbc);
3138 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003139 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003140 ALOGE("addClientLayer called with a removed parent");
3141 return NAME_NOT_FOUND;
3142 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003143 parent->addChild(lbc);
3144 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003145
Yiwei Zhang243b3782018-05-15 17:40:04 -07003146 if (gbc != nullptr) {
3147 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3148 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3149 mMaxGraphicBufferProducerListSize,
3150 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3151 mGraphicBufferProducerList.size(),
3152 mMaxGraphicBufferProducerListSize, mNumLayers);
3153 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003154 mLayersAdded = true;
3155 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003156 }
3157
Mathias Agopian96f08192010-06-02 23:28:45 -07003158 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003159 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003160
Dan Stoza7d89d062015-04-30 13:29:25 -07003161 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003162}
3163
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003164status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003165 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003166 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3167}
Robert Carr7f9b8992017-03-10 11:08:39 -08003168
chaviwca27f252018-02-06 16:46:39 -08003169status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3170 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003171 if (layer->isPendingRemoval()) {
3172 return NO_ERROR;
3173 }
3174
Robert Carr1f0a16a2016-10-24 16:27:39 -07003175 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003176 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003177 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003178 if (topLevelOnly) {
3179 return NO_ERROR;
3180 }
3181
Chia-I Wu98f1c102017-05-30 14:54:08 -07003182 sp<Layer> ancestor = p;
3183 while (ancestor->getParent() != nullptr) {
3184 ancestor = ancestor->getParent();
3185 }
3186 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3187 ALOGE("removeLayer called with a layer whose parent has been removed");
3188 return NAME_NOT_FOUND;
3189 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003190
3191 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003192 } else {
3193 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003194 }
3195
Robert Carr136e2f62017-02-08 17:54:29 -08003196 // As a matter of normal operation, the LayerCleaner will produce a second
3197 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3198 // so we will succeed in promoting it, but it's already been removed
3199 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3200 // otherwise something has gone wrong and we are leaking the layer.
3201 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003202 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3203 layer->getName().string(),
3204 (p != nullptr) ? p->getName().string() : "no-parent");
3205 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003206 } else if (index < 0) {
3207 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003208 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003209
Chia-I Wuc6657022017-08-15 11:18:17 -07003210 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003211 mLayersPendingRemoval.add(layer);
3212 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003213 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003214 setTransactionFlags(eTransactionNeeded);
3215 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003216}
3217
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003218uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003219 return android_atomic_release_load(&mTransactionFlags);
3220}
3221
Mathias Agopian3f844832013-08-07 21:24:32 -07003222uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003223 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3224}
3225
Mathias Agopian3f844832013-08-07 21:24:32 -07003226uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003227 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3228}
3229
3230uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3231 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003232 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003233 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003234 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003235 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003236 }
3237 return old;
3238}
3239
chaviwca27f252018-02-06 16:46:39 -08003240bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3241 for (const ComposerState& state : states) {
3242 // Here we need to check that the interface we're given is indeed
3243 // one of our own. A malicious client could give us a nullptr
3244 // IInterface, or one of its own or even one of our own but a
3245 // different type. All these situations would cause us to crash.
3246 if (state.client == nullptr) {
3247 return true;
3248 }
3249
3250 sp<IBinder> binder = IInterface::asBinder(state.client);
3251 if (binder == nullptr) {
3252 return true;
3253 }
3254
3255 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3256 return true;
3257 }
3258 }
3259 return false;
3260}
3261
Mathias Agopian8b33f032012-07-24 20:43:54 -07003262void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003263 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003264 const Vector<DisplayState>& displays,
3265 uint32_t flags)
3266{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003267 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003268 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003269 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003270
chaviwca27f252018-02-06 16:46:39 -08003271 if (containsAnyInvalidClientState(states)) {
3272 return;
3273 }
3274
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003275 if (flags & eAnimation) {
3276 // For window updates that are part of an animation we must wait for
3277 // previous animation "frames" to be handled.
3278 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003279 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003280 if (CC_UNLIKELY(err != NO_ERROR)) {
3281 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003282 // caller after a few seconds.
3283 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3284 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003285 mAnimTransactionPending = false;
3286 break;
3287 }
3288 }
3289 }
3290
chaviwca27f252018-02-06 16:46:39 -08003291 for (const DisplayState& display : displays) {
3292 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003293 }
3294
chaviwca27f252018-02-06 16:46:39 -08003295 for (const ComposerState& state : states) {
3296 transactionFlags |= setClientStateLocked(state);
3297 }
3298
3299 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3300 // as destroyed should only occur after setting all other states. This is to allow for a
3301 // child re-parent to happen before marking its original parent as destroyed (which would
3302 // then mark the child as destroyed).
3303 for (const ComposerState& state : states) {
3304 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003305 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003306
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003307 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3308 // anyway. This can be used as a flush mechanism for previous async transactions.
3309 // Empty animation transaction can be used to simulate back-pressure, so also force a
3310 // transaction for empty animation transactions.
3311 if (transactionFlags == 0 &&
3312 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003313 transactionFlags = eTransactionNeeded;
3314 }
3315
Mathias Agopian386aa982011-11-07 21:58:03 -08003316 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003317 if (mInterceptor->isEnabled()) {
3318 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003319 }
Irvel468051e2016-06-13 16:44:44 -07003320
Mathias Agopian386aa982011-11-07 21:58:03 -08003321 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003322 const auto start = (flags & eEarlyWakeup)
3323 ? VSyncModulator::TransactionStart::EARLY
3324 : VSyncModulator::TransactionStart::NORMAL;
3325 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003326
3327 // if this is a synchronous transaction, wait for it to take effect
3328 // before returning.
3329 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003330 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003331 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003332 if (flags & eAnimation) {
3333 mAnimTransactionPending = true;
3334 }
3335 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003336 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3337 if (CC_UNLIKELY(err != NO_ERROR)) {
3338 // just in case something goes wrong in SF, return to the
3339 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003340 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3341 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003342 break;
3343 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003344 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003345 }
3346}
3347
Mathias Agopiane57f2922012-08-09 16:29:12 -07003348uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3349{
Jesse Hall9a143922012-10-04 16:29:19 -07003350 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3351 if (dpyIdx < 0)
3352 return 0;
3353
Mathias Agopiane57f2922012-08-09 16:29:12 -07003354 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003355 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003356 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003357 const uint32_t what = s.what;
3358 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003359 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003360 disp.surface = s.surface;
3361 flags |= eDisplayTransactionNeeded;
3362 }
3363 }
3364 if (what & DisplayState::eLayerStackChanged) {
3365 if (disp.layerStack != s.layerStack) {
3366 disp.layerStack = s.layerStack;
3367 flags |= eDisplayTransactionNeeded;
3368 }
3369 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003370 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003371 if (disp.orientation != s.orientation) {
3372 disp.orientation = s.orientation;
3373 flags |= eDisplayTransactionNeeded;
3374 }
3375 if (disp.frame != s.frame) {
3376 disp.frame = s.frame;
3377 flags |= eDisplayTransactionNeeded;
3378 }
3379 if (disp.viewport != s.viewport) {
3380 disp.viewport = s.viewport;
3381 flags |= eDisplayTransactionNeeded;
3382 }
3383 }
Michael Lentine47e45402014-07-18 15:34:25 -07003384 if (what & DisplayState::eDisplaySizeChanged) {
3385 if (disp.width != s.width) {
3386 disp.width = s.width;
3387 flags |= eDisplayTransactionNeeded;
3388 }
3389 if (disp.height != s.height) {
3390 disp.height = s.height;
3391 flags |= eDisplayTransactionNeeded;
3392 }
3393 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003394 }
3395 return flags;
3396}
3397
chaviwca27f252018-02-06 16:46:39 -08003398uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3399 const layer_state_t& s = composerState.state;
3400 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3401
Mathias Agopian13127d82013-03-05 17:47:11 -08003402 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003403 if (layer == nullptr) {
3404 return 0;
3405 }
3406
3407 if (layer->isPendingRemoval()) {
3408 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3409 return 0;
3410 }
3411
3412 uint32_t flags = 0;
3413
3414 const uint32_t what = s.what;
3415 bool geometryAppliesWithResize =
3416 what & layer_state_t::eGeometryAppliesWithResize;
3417 if (what & layer_state_t::ePositionChanged) {
3418 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3419 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003420 }
chaviw8b3871a2017-11-01 17:41:01 -07003421 }
3422 if (what & layer_state_t::eLayerChanged) {
3423 // NOTE: index needs to be calculated before we update the state
3424 const auto& p = layer->getParent();
3425 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003426 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003427 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003428 mCurrentState.layersSortedByZ.removeAt(idx);
3429 mCurrentState.layersSortedByZ.add(layer);
3430 // we need traversal (state changed)
3431 // AND transaction (list changed)
3432 flags |= eTransactionNeeded|eTraversalNeeded;
3433 }
chaviw8b3871a2017-11-01 17:41:01 -07003434 } else {
3435 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003436 flags |= eTransactionNeeded|eTraversalNeeded;
3437 }
3438 }
chaviw8b3871a2017-11-01 17:41:01 -07003439 }
3440 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003441 // NOTE: index needs to be calculated before we update the state
3442 const auto& p = layer->getParent();
3443 if (p == nullptr) {
3444 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3445 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3446 mCurrentState.layersSortedByZ.removeAt(idx);
3447 mCurrentState.layersSortedByZ.add(layer);
3448 // we need traversal (state changed)
3449 // AND transaction (list changed)
3450 flags |= eTransactionNeeded|eTraversalNeeded;
3451 }
3452 } else {
3453 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3454 flags |= eTransactionNeeded|eTraversalNeeded;
3455 }
chaviw8b3871a2017-11-01 17:41:01 -07003456 }
3457 }
3458 if (what & layer_state_t::eSizeChanged) {
3459 if (layer->setSize(s.w, s.h)) {
3460 flags |= eTraversalNeeded;
3461 }
3462 }
3463 if (what & layer_state_t::eAlphaChanged) {
3464 if (layer->setAlpha(s.alpha))
3465 flags |= eTraversalNeeded;
3466 }
3467 if (what & layer_state_t::eColorChanged) {
3468 if (layer->setColor(s.color))
3469 flags |= eTraversalNeeded;
3470 }
3471 if (what & layer_state_t::eMatrixChanged) {
3472 if (layer->setMatrix(s.matrix))
3473 flags |= eTraversalNeeded;
3474 }
3475 if (what & layer_state_t::eTransparentRegionChanged) {
3476 if (layer->setTransparentRegionHint(s.transparentRegion))
3477 flags |= eTraversalNeeded;
3478 }
3479 if (what & layer_state_t::eFlagsChanged) {
3480 if (layer->setFlags(s.flags, s.mask))
3481 flags |= eTraversalNeeded;
3482 }
3483 if (what & layer_state_t::eCropChanged) {
3484 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3485 flags |= eTraversalNeeded;
3486 }
3487 if (what & layer_state_t::eFinalCropChanged) {
3488 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3489 flags |= eTraversalNeeded;
3490 }
3491 if (what & layer_state_t::eLayerStackChanged) {
3492 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3493 // We only allow setting layer stacks for top level layers,
3494 // everything else inherits layer stack from its parent.
3495 if (layer->hasParent()) {
3496 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3497 layer->getName().string());
3498 } else if (idx < 0) {
3499 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3500 "that also does not appear in the top level layer list. Something"
3501 " has gone wrong.", layer->getName().string());
3502 } else if (layer->setLayerStack(s.layerStack)) {
3503 mCurrentState.layersSortedByZ.removeAt(idx);
3504 mCurrentState.layersSortedByZ.add(layer);
3505 // we need traversal (state changed)
3506 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003507 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003508 }
3509 }
3510 if (what & layer_state_t::eDeferTransaction) {
3511 if (s.barrierHandle != nullptr) {
3512 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3513 } else if (s.barrierGbp != nullptr) {
3514 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3515 if (authenticateSurfaceTextureLocked(gbp)) {
3516 const auto& otherLayer =
3517 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3518 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3519 } else {
3520 ALOGE("Attempt to defer transaction to to an"
3521 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003522 }
3523 }
chaviw8b3871a2017-11-01 17:41:01 -07003524 // We don't trigger a traversal here because if no other state is
3525 // changed, we don't want this to cause any more work
3526 }
3527 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003528 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003529 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003530 if (!hadParent) {
3531 mCurrentState.layersSortedByZ.remove(layer);
3532 }
chaviw8b3871a2017-11-01 17:41:01 -07003533 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003534 }
chaviw8b3871a2017-11-01 17:41:01 -07003535 }
3536 if (what & layer_state_t::eReparentChildren) {
3537 if (layer->reparentChildren(s.reparentHandle)) {
3538 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003539 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003540 }
chaviw8b3871a2017-11-01 17:41:01 -07003541 if (what & layer_state_t::eDetachChildren) {
3542 layer->detachChildren();
3543 }
3544 if (what & layer_state_t::eOverrideScalingModeChanged) {
3545 layer->setOverrideScalingMode(s.overrideScalingMode);
3546 // We don't trigger a traversal here because if no other state is
3547 // changed, we don't want this to cause any more work
3548 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003549 return flags;
3550}
3551
chaviwca27f252018-02-06 16:46:39 -08003552void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3553 const layer_state_t& state = composerState.state;
3554 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3555
3556 sp<Layer> layer(client->getLayerUser(state.surface));
3557 if (layer == nullptr) {
3558 return;
3559 }
3560
3561 if (layer->isPendingRemoval()) {
3562 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3563 return;
3564 }
3565
3566 if (state.what & layer_state_t::eDestroySurface) {
3567 removeLayerLocked(mStateLock, layer);
3568 }
3569}
3570
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003571status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003572 const String8& name,
3573 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003574 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003575 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003576 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003577{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003578 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003579 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003580 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003581 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003582 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003583
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003584 status_t result = NO_ERROR;
3585
3586 sp<Layer> layer;
3587
Cody Northropbc755282017-03-31 12:00:08 -06003588 String8 uniqueName = getUniqueLayerName(name);
3589
Mathias Agopian3165cc22012-08-08 19:42:09 -07003590 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3591 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003592 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003593 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003594 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003595
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003596 break;
chaviw13fdc492017-06-27 12:40:18 -07003597 case ISurfaceComposerClient::eFXSurfaceColor:
3598 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003599 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003600 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003601 break;
3602 default:
3603 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003604 break;
3605 }
3606
Dan Stoza7d89d062015-04-30 13:29:25 -07003607 if (result != NO_ERROR) {
3608 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003609 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003610
Chia-I Wuab0c3192017-08-01 11:29:00 -07003611 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3612 // TODO b/64227542
3613 if (windowType == 441731) {
3614 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3615 layer->setPrimaryDisplayOnly();
3616 }
3617
Albert Chaulk479c60c2017-01-27 14:21:34 -05003618 layer->setInfo(windowType, ownerUid);
3619
Robert Carr1f0a16a2016-10-24 16:27:39 -07003620 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003621 if (result != NO_ERROR) {
3622 return result;
3623 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003624 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003625
3626 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003627 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003628}
3629
Cody Northropbc755282017-03-31 12:00:08 -06003630String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3631{
3632 bool matchFound = true;
3633 uint32_t dupeCounter = 0;
3634
3635 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3636 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3637
3638 // Loop over layers until we're sure there is no matching name
3639 while (matchFound) {
3640 matchFound = false;
3641 mDrawingState.traverseInZOrder([&](Layer* layer) {
3642 if (layer->getName() == uniqueName) {
3643 matchFound = true;
3644 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3645 }
3646 });
3647 }
3648
3649 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3650
3651 return uniqueName;
3652}
3653
David Sodman0c69cad2017-08-21 12:12:51 -07003654status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003655 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3656 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003657{
3658 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003659 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003660 case PIXEL_FORMAT_TRANSPARENT:
3661 case PIXEL_FORMAT_TRANSLUCENT:
3662 format = PIXEL_FORMAT_RGBA_8888;
3663 break;
3664 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003665 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003666 break;
3667 }
3668
David Sodman0c69cad2017-08-21 12:12:51 -07003669 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3670 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003671 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003672 *handle = layer->getHandle();
3673 *gbp = layer->getProducer();
3674 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003675 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003676
David Sodman0c69cad2017-08-21 12:12:51 -07003677 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003678 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003679}
3680
chaviw13fdc492017-06-27 12:40:18 -07003681status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003682 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003683 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003684{
chaviw13fdc492017-06-27 12:40:18 -07003685 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003686 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003687 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003688}
3689
Mathias Agopianac9fa422013-02-11 16:40:36 -08003690status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003691{
Robert Carr9524cb32017-02-13 11:32:32 -08003692 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003693 status_t err = NO_ERROR;
3694 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003695 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003696 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003697 err = removeLayer(l);
3698 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3699 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003700 }
3701 return err;
3702}
3703
Mathias Agopian13127d82013-03-05 17:47:11 -08003704status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003705{
Mathias Agopian67106042013-03-14 19:18:13 -07003706 // called by ~LayerCleaner() when all references to the IBinder (handle)
3707 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003708 sp<Layer> l = layer.promote();
3709 if (l == nullptr) {
3710 // The layer has already been removed, carry on
3711 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003712 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003713 // If we have a parent, then we can continue to live as long as it does.
3714 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003715}
3716
Mathias Agopianb60314a2012-04-10 22:09:54 -07003717// ---------------------------------------------------------------------------
3718
Andy McFadden13a082e2012-08-24 10:16:42 -07003719void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003720 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003721 Vector<ComposerState> state;
3722 Vector<DisplayState> displays;
3723 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003724 d.what = DisplayState::eDisplayProjectionChanged |
3725 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003726 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003727 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003728 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003729 d.frame.makeInvalid();
3730 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003731 d.width = 0;
3732 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003733 displays.add(d);
3734 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003735 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3736 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003737
David Sodman105b7dc2017-11-04 20:28:14 -07003738 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003739 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003740 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003741
Brian Andersond0010582017-03-07 13:20:31 -08003742 // Use phase of 0 since phase is not known.
3743 // Use latency of 0, which will snap to the ideal latency.
3744 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003745}
3746
3747void SurfaceFlinger::initializeDisplays() {
3748 class MessageScreenInitialized : public MessageBase {
3749 SurfaceFlinger* flinger;
3750 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003751 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003752 virtual bool handler() {
3753 flinger->onInitializeDisplays();
3754 return true;
3755 }
3756 };
3757 sp<MessageBase> msg = new MessageScreenInitialized(this);
3758 postMessageAsync(msg); // we may be called from main thread, use async message
3759}
3760
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003761void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003762 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003763 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3764 this);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003765 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003766
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003767 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003768 return;
3769 }
3770
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003771 hw->setPowerMode(mode);
Dominik Laskowski281644e2018-04-19 15:47:35 -07003772 if (hw->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003773 ALOGW("Trying to set power mode for virtual display");
3774 return;
3775 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003776
Lloyd Pique4dccc412018-01-22 17:21:36 -08003777 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003778 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003779 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3780 if (idx < 0) {
3781 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3782 return;
3783 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003784 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003785 }
3786
Dominik Laskowski281644e2018-04-19 15:47:35 -07003787 int32_t type = hw->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003788 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003789 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003790 getHwComposer().setPowerMode(type, mode);
Dominik Laskowski281644e2018-04-19 15:47:35 -07003791 if (hw->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003792 // FIXME: eventthread only knows about the main display right now
3793 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003794 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003795 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003796
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003797 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003798 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003799 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003800
3801 struct sched_param param = {0};
3802 param.sched_priority = 1;
3803 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3804 ALOGW("Couldn't set SCHED_FIFO on display on");
3805 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003806 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003807 // Turn off the display
3808 struct sched_param param = {0};
3809 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3810 ALOGW("Couldn't set SCHED_OTHER on display off");
3811 }
3812
Dominik Laskowski281644e2018-04-19 15:47:35 -07003813 if (hw->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003814 disableHardwareVsync(true); // also cancels any in-progress resync
3815
Mathias Agopiancde87a32012-09-13 14:09:01 -07003816 // FIXME: eventthread only knows about the main display right now
3817 mEventThread->onScreenReleased();
3818 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003819
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003820 getHwComposer().setPowerMode(type, mode);
3821 mVisibleRegionsDirty = true;
3822 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003823 } else if (mode == HWC_POWER_MODE_DOZE ||
3824 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003825 // Update display while dozing
3826 getHwComposer().setPowerMode(type, mode);
Dominik Laskowski281644e2018-04-19 15:47:35 -07003827 if (hw->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003828 // FIXME: eventthread only knows about the main display right now
3829 mEventThread->onScreenAcquired();
3830 resyncToHardwareVsync(true);
3831 }
3832 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3833 // Leave display going to doze
Dominik Laskowski281644e2018-04-19 15:47:35 -07003834 if (hw->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003835 disableHardwareVsync(true); // also cancels any in-progress resync
3836 // FIXME: eventthread only knows about the main display right now
3837 mEventThread->onScreenReleased();
3838 }
3839 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003840 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003841 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003842 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003843 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003844 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003845}
3846
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003847void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3848 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003849 SurfaceFlinger& mFlinger;
3850 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003851 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003852 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003853 MessageSetPowerMode(SurfaceFlinger& flinger,
3854 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3855 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003856 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003857 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003858 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003859 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003860 mMode, mDisplay.get());
Dominik Laskowski281644e2018-04-19 15:47:35 -07003861 } else if (hw->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003862 ALOGW("Attempt to set power mode = %d for virtual display",
3863 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003864 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003865 mFlinger.setPowerModeInternal(
3866 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003867 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003868 return true;
3869 }
3870 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003871 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003872 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003873}
3874
3875// ---------------------------------------------------------------------------
3876
Lloyd Pique755e3192018-01-31 16:46:15 -08003877status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3878 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003879 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003880
Mathias Agopianbd115332013-04-18 16:41:04 -07003881 IPCThreadState* ipc = IPCThreadState::self();
3882 const int pid = ipc->getCallingPid();
3883 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003884
Mathias Agopianbd115332013-04-18 16:41:04 -07003885 if ((uid != AID_SHELL) &&
3886 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003887 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003888 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003889 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003890 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003891 // (this would indicate SF is stuck, but we want to be able to
3892 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003893 status_t err = mStateLock.timedLock(s2ns(1));
3894 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003895 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003896 result.appendFormat(
3897 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3898 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003899 }
3900
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003901 bool dumpAll = true;
3902 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003903 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003904
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003905 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003906 if ((index < numArgs) &&
3907 (args[index] == String16("--list"))) {
3908 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003909 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003910 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003911 }
3912
3913 if ((index < numArgs) &&
3914 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003915 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003916 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003917 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003918 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003919
3920 if ((index < numArgs) &&
3921 (args[index] == String16("--latency-clear"))) {
3922 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003923 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003924 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003925 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003926
3927 if ((index < numArgs) &&
3928 (args[index] == String16("--dispsync"))) {
3929 index++;
3930 mPrimaryDispSync.dump(result);
3931 dumpAll = false;
3932 }
Dan Stozab90cf072015-03-05 11:05:59 -08003933
3934 if ((index < numArgs) &&
3935 (args[index] == String16("--static-screen"))) {
3936 index++;
3937 dumpStaticScreenStats(result);
3938 dumpAll = false;
3939 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003940
3941 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003942 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003943 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003944 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003945 dumpAll = false;
3946 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003947
3948 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3949 index++;
3950 dumpWideColorInfo(result);
3951 dumpAll = false;
3952 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003953
3954 if ((index < numArgs) &&
3955 (args[index] == String16("--enable-layer-stats"))) {
3956 index++;
3957 mLayerStats.enable();
3958 dumpAll = false;
3959 }
3960
3961 if ((index < numArgs) &&
3962 (args[index] == String16("--disable-layer-stats"))) {
3963 index++;
3964 mLayerStats.disable();
3965 dumpAll = false;
3966 }
3967
3968 if ((index < numArgs) &&
3969 (args[index] == String16("--clear-layer-stats"))) {
3970 index++;
3971 mLayerStats.clear();
3972 dumpAll = false;
3973 }
3974
3975 if ((index < numArgs) &&
3976 (args[index] == String16("--dump-layer-stats"))) {
3977 index++;
3978 mLayerStats.dump(result);
3979 dumpAll = false;
3980 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07003981
3982 if ((index < numArgs) &&
3983 (args[index] == String16("--display-identification"))) {
3984 index++;
3985 dumpDisplayIdentificationData(result);
3986 dumpAll = false;
3987 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003988
3989 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3990 index++;
3991 mTimeStats.parseArgs(asProto, args, index, result);
3992 dumpAll = false;
3993 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003994 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003995
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003996 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003997 if (asProto) {
3998 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3999 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4000 } else {
4001 dumpAllLocked(args, index, result);
4002 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004003 }
4004
Mathias Agopian9795c422009-08-26 16:36:26 -07004005 if (locked) {
4006 mStateLock.unlock();
4007 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004008 }
4009 write(fd, result.string(), result.size());
4010 return NO_ERROR;
4011}
4012
Dan Stozac7014012014-02-14 15:03:43 -08004013void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4014 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004015{
Robert Carr2047fae2016-11-28 14:09:09 -08004016 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004017 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004018 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004019}
4020
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004021void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004022 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004023{
4024 String8 name;
4025 if (index < args.size()) {
4026 name = String8(args[index]);
4027 index++;
4028 }
4029
David Sodman105b7dc2017-11-04 20:28:14 -07004030 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004031 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08004032 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004033
4034 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004035 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004036 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004037 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004038 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004039 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004040 }
Robert Carr2047fae2016-11-28 14:09:09 -08004041 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004042 }
4043}
4044
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004045void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004046 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004047{
4048 String8 name;
4049 if (index < args.size()) {
4050 name = String8(args[index]);
4051 index++;
4052 }
4053
Robert Carr2047fae2016-11-28 14:09:09 -08004054 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004055 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004056 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004057 }
Robert Carr2047fae2016-11-28 14:09:09 -08004058 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004059
Svetoslavd85084b2014-03-20 10:28:31 -07004060 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004061}
4062
Jamie Gennis6547ff42013-07-16 20:12:42 -07004063// This should only be called from the main thread. Otherwise it would need
4064// the lock and should use mCurrentState rather than mDrawingState.
4065void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004066 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004067 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004068 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004069
4070 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4071}
4072
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004073void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004074{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004075 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004076
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004077 if (isLayerTripleBufferingDisabled())
4078 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004079
4080 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004081 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004082 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004083 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004084 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4085 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004086 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004087}
4088
Dan Stozab90cf072015-03-05 11:05:59 -08004089void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4090{
4091 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004092 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4093 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004094 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004095 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004096 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4097 b + 1, bucketTimeSec, percent);
4098 }
David Sodman4a36e932017-11-07 14:29:47 -08004099 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004100 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004101 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004102 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004103 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004104}
4105
Dan Stozae77c7662016-05-13 11:37:28 -07004106void SurfaceFlinger::recordBufferingStats(const char* layerName,
4107 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004108 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4109 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004110 for (const auto& segment : history) {
4111 if (!segment.usedThirdBuffer) {
4112 stats.twoBufferTime += segment.totalTime;
4113 }
4114 if (segment.occupancyAverage < 1.0f) {
4115 stats.doubleBufferedTime += segment.totalTime;
4116 } else if (segment.occupancyAverage < 2.0f) {
4117 stats.tripleBufferedTime += segment.totalTime;
4118 }
4119 ++stats.numSegments;
4120 stats.totalTime += segment.totalTime;
4121 }
4122}
4123
Brian Andersond6927fb2016-07-23 23:37:30 -07004124void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4125 result.appendFormat("Layer frame timestamps:\n");
4126
4127 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4128 const size_t count = currentLayers.size();
4129 for (size_t i=0 ; i<count ; i++) {
4130 currentLayers[i]->dumpFrameEvents(result);
4131 }
4132}
4133
Dan Stozae77c7662016-05-13 11:37:28 -07004134void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4135 result.append("Buffering stats:\n");
4136 result.append(" [Layer name] <Active time> <Two buffer> "
4137 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004138 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004139 typedef std::tuple<std::string, float, float, float> BufferTuple;
4140 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004141 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004142 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004143 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004144 if (stats.numSegments == 0) {
4145 continue;
4146 }
4147 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4148 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4149 stats.totalTime;
4150 float doubleBufferRatio = static_cast<float>(
4151 stats.doubleBufferedTime) / stats.totalTime;
4152 float tripleBufferRatio = static_cast<float>(
4153 stats.tripleBufferedTime) / stats.totalTime;
4154 sorted.insert({activeTime, {name, twoBufferRatio,
4155 doubleBufferRatio, tripleBufferRatio}});
4156 }
4157 for (const auto& sortedPair : sorted) {
4158 float activeTime = sortedPair.first;
4159 const BufferTuple& values = sortedPair.second;
4160 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4161 std::get<0>(values).c_str(), activeTime,
4162 std::get<1>(values), std::get<2>(values),
4163 std::get<3>(values));
4164 }
4165 result.append("\n");
4166}
4167
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004168void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
4169 for (size_t d = 0; d < mDisplays.size(); d++) {
4170 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4171 const int32_t hwcId = displayDevice->getHwcDisplayId();
4172 const auto displayId = getHwComposer().getHwcDisplayId(hwcId);
4173 if (!displayId) {
4174 continue;
4175 }
4176
4177 result.appendFormat("Display %d: ", hwcId);
4178 uint8_t port;
4179 DisplayIdentificationData data;
4180 if (!getHwComposer().getDisplayIdentificationData(*displayId, &port, &data)) {
4181 result.append("no identification data\n");
4182 continue;
4183 }
4184
4185 if (!isEdid(data)) {
4186 result.append("unknown identification data: ");
4187 for (uint8_t byte : data) {
4188 result.appendFormat("%x ", byte);
4189 }
4190 result.append("\n");
4191 continue;
4192 }
4193
4194 const auto edid = parseEdid(data);
4195 if (!edid) {
4196 result.append("invalid EDID: ");
4197 for (uint8_t byte : data) {
4198 result.appendFormat("%x ", byte);
4199 }
4200 result.append("\n");
4201 continue;
4202 }
4203
4204 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4205 result.append(edid->displayName.data(), edid->displayName.length());
4206 result.append("\"\n");
4207 }
4208 result.append("\n");
4209}
4210
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004211void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4212 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004213 result.appendFormat("DisplayColorSetting: %d\n", mDisplayColorSetting);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004214
4215 // TODO: print out if wide-color mode is active or not
4216
4217 for (size_t d = 0; d < mDisplays.size(); d++) {
4218 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4219 int32_t hwcId = displayDevice->getHwcDisplayId();
4220 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4221 continue;
4222 }
4223
4224 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004225 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004226 for (auto&& mode : modes) {
4227 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4228 }
4229
Peiyong Lina52f0292018-03-14 17:26:31 -07004230 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004231 result.appendFormat(" Current color mode: %s (%d)\n",
4232 decodeColorMode(currentMode).c_str(), currentMode);
4233 }
4234 result.append("\n");
4235}
4236
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004237LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004238 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004239 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4240 const State& state = useDrawing ? mDrawingState : mCurrentState;
4241 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004242 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004243 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004244 });
4245
4246 return layersProto;
4247}
4248
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004249LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4250 LayersProto layersProto;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004251 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004252
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004253 SizeProto* resolution = layersProto.mutable_resolution();
4254 resolution->set_w(displayDevice->getWidth());
4255 resolution->set_h(displayDevice->getHeight());
4256
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004257 layersProto.set_color_mode(decodeColorMode(displayDevice->getActiveColorMode()));
4258 layersProto.set_color_transform(decodeColorTransform(displayDevice->getColorTransform()));
4259 layersProto.set_global_transform(
4260 static_cast<int32_t>(displayDevice->getOrientationTransform()));
4261
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004262 mDrawingState.traverseInZOrder([&](Layer* layer) {
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004263 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004264 LayerProto* layerProto = layersProto.add_layers();
4265 layer->writeToProto(layerProto, hwcId);
4266 }
4267 });
4268
4269 return layersProto;
4270}
4271
Mathias Agopian74d211a2013-04-22 16:55:35 +02004272void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4273 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004274{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004275 bool colorize = false;
4276 if (index < args.size()
4277 && (args[index] == String16("--color"))) {
4278 colorize = true;
4279 index++;
4280 }
4281
4282 Colorizer colorizer(colorize);
4283
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004284 // figure out if we're stuck somewhere
4285 const nsecs_t now = systemTime();
4286 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4287 const nsecs_t inTransaction(mDebugInTransaction);
4288 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4289 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4290
4291 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004292 * Dump library configuration.
4293 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004294
4295 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004296 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004297 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004298 appendSfConfigString(result);
4299 appendUiConfigString(result);
4300 appendGuiConfigString(result);
4301 result.append("\n");
4302
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004303 result.append("\nDisplay identification data:\n");
4304 dumpDisplayIdentificationData(result);
4305
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004306 result.append("\nWide-Color information:\n");
4307 dumpWideColorInfo(result);
4308
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004309 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004310 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004311 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004312 result.append(SyncFeatures::getInstance().toString());
4313 result.append("\n");
4314
David Sodman105b7dc2017-11-04 20:28:14 -07004315 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004316
Andy McFadden41d67d72014-04-25 16:58:34 -07004317 colorizer.bold(result);
4318 result.append("DispSync configuration: ");
4319 colorizer.reset(result);
Dan Stoza84d619e2018-03-28 17:07:36 -07004320 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, early sf phase %" PRId64
4321 " ns, present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4322 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, mVsyncModulator.getEarlyPhaseOffset(),
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004323 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004324 result.append("\n");
4325
Dan Stozab90cf072015-03-05 11:05:59 -08004326 // Dump static screen stats
4327 result.append("\n");
4328 dumpStaticScreenStats(result);
4329 result.append("\n");
4330
Dan Stozae77c7662016-05-13 11:37:28 -07004331 dumpBufferingStats(result);
4332
Andy McFadden4803b742012-09-24 19:07:20 -07004333 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004334 * Dump the visible layer list
4335 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004336 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004337 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004338 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4339 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004340 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004341
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004342 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004343 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004344 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004345 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004346
4347 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004348 * Dump Display state
4349 */
4350
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004351 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004352 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004353 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004354 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4355 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004356 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004357 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004358 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004359
4360 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004361 * Dump SurfaceFlinger global state
4362 */
4363
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004364 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004365 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004366 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004367
Mathias Agopian888c8222012-08-04 21:10:38 -07004368 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004369 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004370
David Sodmanbc815282017-11-05 18:57:52 -08004371 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004372
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004373 if (hw) {
4374 hw->undefinedRegion.dump(result, "undefinedRegion");
4375 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4376 hw->getOrientation(), hw->isDisplayOn());
4377 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004378 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004379 " last eglSwapBuffers() time: %f us\n"
4380 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004381 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004382 " refresh-rate : %f fps\n"
4383 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004384 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004385 " gpu_to_cpu_unsupported : %d\n"
4386 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004387 mLastSwapBufferTime/1000.0,
4388 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004389 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004390 1e9 / activeConfig->getVsyncPeriod(),
4391 activeConfig->getDpiX(),
4392 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004393 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004394
Mathias Agopian74d211a2013-04-22 16:55:35 +02004395 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004396 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004397
Mathias Agopian74d211a2013-04-22 16:55:35 +02004398 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004399 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004400
4401 /*
4402 * VSYNC state
4403 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004404 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004405 result.append("\n");
4406
4407 /*
4408 * HWC layer minidump
4409 */
4410 for (size_t d = 0; d < mDisplays.size(); d++) {
4411 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4412 int32_t hwcId = displayDevice->getHwcDisplayId();
4413 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4414 continue;
4415 }
4416
4417 result.appendFormat("Display %d HWC layers:\n", hwcId);
4418 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004419 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004420 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004421 });
Dan Stozae22aec72016-08-01 13:20:59 -07004422 result.append("\n");
4423 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004424
4425 /*
4426 * Dump HWComposer state
4427 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004428 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004429 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004430 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004431 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004432 result.appendFormat(" h/w composer %s\n",
4433 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004434 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004435
4436 /*
4437 * Dump gralloc state
4438 */
4439 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4440 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004441
4442 /*
4443 * Dump VrFlinger state if in use.
4444 */
4445 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4446 result.append("VrFlinger state:\n");
4447 result.append(mVrFlinger->Dump().c_str());
4448 result.append("\n");
4449 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004450}
4451
Mathias Agopian13127d82013-03-05 17:47:11 -08004452const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004453SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004454 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004455 wp<IBinder> dpy;
4456 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4457 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4458 dpy = mDisplays.keyAt(i);
4459 break;
4460 }
4461 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004462 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004463 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4464 // Just use the primary display so we have something to return
4465 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4466 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004467 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004468}
4469
Keun young Park63f165f2012-08-31 10:53:36 -07004470bool SurfaceFlinger::startDdmConnection()
4471{
4472 void* libddmconnection_dso =
4473 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4474 if (!libddmconnection_dso) {
4475 return false;
4476 }
4477 void (*DdmConnection_start)(const char* name);
4478 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004479 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004480 if (!DdmConnection_start) {
4481 dlclose(libddmconnection_dso);
4482 return false;
4483 }
4484 (*DdmConnection_start)(getServiceName());
4485 return true;
4486}
4487
Chia-I Wu28f320b2018-05-03 11:02:56 -07004488void SurfaceFlinger::updateColorMatrixLocked() {
4489 mat4 colorMatrix;
4490 if (mGlobalSaturationFactor != 1.0f) {
4491 // Rec.709 luma coefficients
4492 float3 luminance{0.213f, 0.715f, 0.072f};
4493 luminance *= 1.0f - mGlobalSaturationFactor;
4494 mat4 saturationMatrix = mat4(
4495 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4496 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4497 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4498 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4499 );
4500 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4501 } else {
4502 colorMatrix = mClientColorMatrix * mDaltonizer();
4503 }
4504
4505 if (mCurrentState.colorMatrix != colorMatrix) {
4506 mCurrentState.colorMatrix = colorMatrix;
4507 mCurrentState.colorMatrixChanged = true;
4508 setTransactionFlags(eTransactionNeeded);
4509 }
4510}
4511
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004512status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004513 switch (code) {
4514 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004515 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004516 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004517 case CLEAR_ANIMATION_FRAME_STATS:
4518 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004519 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004520 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004521 case ENABLE_VSYNC_INJECTIONS:
4522 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004523 {
4524 // codes that require permission check
4525 IPCThreadState* ipc = IPCThreadState::self();
4526 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004527 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004528 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004529 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004530 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004531 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004532 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004533 break;
4534 }
Robert Carr1db73f62016-12-21 12:58:51 -08004535 /*
4536 * Calling setTransactionState is safe, because you need to have been
4537 * granted a reference to Client* and Handle* to do anything with it.
4538 *
4539 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4540 */
4541 case SET_TRANSACTION_STATE:
4542 case CREATE_SCOPED_CONNECTION:
4543 {
4544 return OK;
4545 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004546 case CAPTURE_SCREEN:
4547 {
4548 // codes that require permission check
4549 IPCThreadState* ipc = IPCThreadState::self();
4550 const int pid = ipc->getCallingPid();
4551 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004552 if ((uid != AID_GRAPHICS) &&
4553 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004554 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004555 return PERMISSION_DENIED;
4556 }
4557 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004558 }
chaviwa76b2712017-09-20 12:02:26 -07004559 case CAPTURE_LAYERS: {
4560 IPCThreadState* ipc = IPCThreadState::self();
4561 const int pid = ipc->getCallingPid();
4562 const int uid = ipc->getCallingUid();
4563 if ((uid != AID_GRAPHICS) &&
4564 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4565 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4566 return PERMISSION_DENIED;
4567 }
4568 break;
4569 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004570 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004571 return OK;
4572}
4573
4574status_t SurfaceFlinger::onTransact(
4575 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4576{
4577 status_t credentialCheck = CheckTransactCodeCredentials(code);
4578 if (credentialCheck != OK) {
4579 return credentialCheck;
4580 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004581
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004582 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4583 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004584 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004585 IPCThreadState* ipc = IPCThreadState::self();
4586 const int uid = ipc->getCallingUid();
4587 if (CC_UNLIKELY(uid != AID_SYSTEM
4588 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004589 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004590 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004591 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004592 return PERMISSION_DENIED;
4593 }
4594 int n;
4595 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004596 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004597 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004598 return NO_ERROR;
4599 case 1002: // SHOW_UPDATES
4600 n = data.readInt32();
4601 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004602 invalidateHwcGeometry();
4603 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004604 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004605 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004606 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004607 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004608 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004609 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004610 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004611 setTransactionFlags(
4612 eTransactionNeeded|
4613 eDisplayTransactionNeeded|
4614 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004615 return NO_ERROR;
4616 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004617 case 1006:{ // send empty update
4618 signalRefresh();
4619 return NO_ERROR;
4620 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004621 case 1008: // toggle use of hw composer
4622 n = data.readInt32();
4623 mDebugDisableHWC = n ? 1 : 0;
4624 invalidateHwcGeometry();
4625 repaintEverything();
4626 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004627 case 1009: // toggle use of transform hint
4628 n = data.readInt32();
4629 mDebugDisableTransformHint = n ? 1 : 0;
4630 invalidateHwcGeometry();
4631 repaintEverything();
4632 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004633 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004634 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004635 reply->writeInt32(0);
4636 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004637 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004638 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004639 return NO_ERROR;
4640 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004641 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004642 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004643 return NO_ERROR;
4644 }
4645 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004646 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004647 // daltonize
4648 n = data.readInt32();
4649 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004650 case 1:
4651 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4652 break;
4653 case 2:
4654 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4655 break;
4656 case 3:
4657 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4658 break;
4659 default:
4660 mDaltonizer.setType(ColorBlindnessType::None);
4661 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004662 }
4663 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004664 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004665 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004666 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004667 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004668
4669 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004670 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004671 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004672 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004673 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004674 // apply a color matrix
4675 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004676 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004677 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004678 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004679 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004680 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004681 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004682 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004683 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004684 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004685 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004686
4687 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4688 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004689 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004690 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4691 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4692 }
4693
Chia-I Wu28f320b2018-05-03 11:02:56 -07004694 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004695 return NO_ERROR;
4696 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004697 // This is an experimental interface
4698 // Needs to be shifted to proper binder interface when we productize
4699 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004700 n = data.readInt32();
4701 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004702 return NO_ERROR;
4703 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004704 case 1017: {
4705 n = data.readInt32();
4706 mForceFullDamage = static_cast<bool>(n);
4707 return NO_ERROR;
4708 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004709 case 1018: { // Modify Choreographer's phase offset
4710 n = data.readInt32();
4711 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4712 return NO_ERROR;
4713 }
4714 case 1019: { // Modify SurfaceFlinger's phase offset
4715 n = data.readInt32();
4716 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4717 return NO_ERROR;
4718 }
Irvel468051e2016-06-13 16:44:44 -07004719 case 1020: { // Layer updates interceptor
4720 n = data.readInt32();
4721 if (n) {
4722 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004723 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004724 }
4725 else{
4726 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004727 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004728 }
4729 return NO_ERROR;
4730 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004731 case 1021: { // Disable HWC virtual displays
4732 n = data.readInt32();
4733 mUseHwcVirtualDisplays = !n;
4734 return NO_ERROR;
4735 }
Romain Guy0147a172017-06-01 13:53:56 -07004736 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004737 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004738 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004739
Chia-I Wu28f320b2018-05-03 11:02:56 -07004740 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004741 return NO_ERROR;
4742 }
Romain Guy54f154a2017-10-24 21:40:32 +01004743 case 1023: { // Set native mode
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004744 int32_t value = data.readInt32();
4745 if (value > 2) {
4746 return BAD_VALUE;
4747 }
4748 if (value == 2 && !mBuiltinDisplaySupportsEnhance) {
4749 return BAD_VALUE;
4750 }
Romain Guy54f154a2017-10-24 21:40:32 +01004751
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004752 mDisplayColorSetting = toDisplayColorSetting(value);
Romain Guy54f154a2017-10-24 21:40:32 +01004753 invalidateHwcGeometry();
4754 repaintEverything();
4755 return NO_ERROR;
4756 }
4757 case 1024: { // Is wide color gamut rendering/color management supported?
4758 reply->writeBool(hasWideColorDisplay);
4759 return NO_ERROR;
4760 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004761 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004762 n = data.readInt32();
4763 if (n) {
4764 ALOGV("LayerTracing enabled");
4765 mTracing.enable();
4766 doTracing("tracing.enable");
4767 reply->writeInt32(NO_ERROR);
4768 } else {
4769 ALOGV("LayerTracing disabled");
4770 status_t err = mTracing.disable();
4771 reply->writeInt32(err);
4772 }
4773 return NO_ERROR;
4774 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004775 case 1026: { // Get layer tracing status
4776 reply->writeBool(mTracing.isEnabled());
4777 return NO_ERROR;
4778 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004779 // Is a DisplayColorSetting supported?
4780 case 1027: {
4781 int32_t value = data.readInt32();
4782 switch (value) {
4783 case 0:
4784 reply->writeBool(hasWideColorDisplay);
4785 return NO_ERROR;
4786 case 1:
4787 reply->writeBool(true);
4788 return NO_ERROR;
4789 case 2:
4790 reply->writeBool(mBuiltinDisplaySupportsEnhance);
4791 return NO_ERROR;
4792 default:
4793 return BAD_VALUE;
4794 }
4795 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004796 }
4797 }
4798 return err;
4799}
4800
Steven Thomas6d8110b2017-08-31 18:24:21 -07004801void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004802 android_atomic_or(1, &mRepaintEverything);
4803 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004804}
4805
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004806// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4807class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004808public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004809 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4810 ~WindowDisconnector() {
4811 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004812 }
4813
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004814private:
4815 ANativeWindow* mWindow;
4816 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004817};
4818
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004819status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4820 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4821 int32_t minLayerZ, int32_t maxLayerZ,
4822 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004823 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004824 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004825
chaviwa76b2712017-09-20 12:02:26 -07004826 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4827
4828 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004829 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4830
chaviwa76b2712017-09-20 12:02:26 -07004831 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4832
4833 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4834 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004835 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004836}
4837
4838status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004839 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004840 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004841 ATRACE_CALL();
4842
4843 class LayerRenderArea : public RenderArea {
4844 public:
Robert Carr578038f2018-03-09 12:25:24 -08004845 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4846 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004847 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004848 mLayer(layer),
4849 mCrop(crop),
4850 mFlinger(flinger),
4851 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004852 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004853 Rect getBounds() const override {
4854 const Layer::State& layerState(mLayer->getDrawingState());
4855 return Rect(layerState.active.w, layerState.active.h);
4856 }
4857 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4858 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4859 bool isSecure() const override { return false; }
4860 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004861 Rect getSourceCrop() const override {
4862 if (mCrop.isEmpty()) {
4863 return getBounds();
4864 } else {
4865 return mCrop;
4866 }
4867 }
Robert Carr578038f2018-03-09 12:25:24 -08004868 class ReparentForDrawing {
4869 public:
4870 const sp<Layer>& oldParent;
4871 const sp<Layer>& newParent;
4872
4873 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4874 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004875 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004876 }
Robert Carr15eae092018-03-23 13:43:53 -07004877 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004878 };
4879
4880 void render(std::function<void()> drawLayers) override {
4881 if (!mChildrenOnly) {
4882 mTransform = mLayer->getTransform().inverse();
4883 drawLayers();
4884 } else {
4885 Rect bounds = getBounds();
4886 screenshotParentLayer =
4887 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4888 bounds.getWidth(), bounds.getHeight(), 0);
4889
4890 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4891 drawLayers();
4892 }
4893 }
chaviwa76b2712017-09-20 12:02:26 -07004894
chaviwa76b2712017-09-20 12:02:26 -07004895 private:
chaviw7206d492017-11-10 16:16:12 -08004896 const sp<Layer> mLayer;
4897 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004898
4899 // In the "childrenOnly" case we reparent the children to a screenshot
4900 // layer which has no properties set and which does not draw.
4901 sp<ContainerLayer> screenshotParentLayer;
4902 Transform mTransform;
4903
4904 SurfaceFlinger* mFlinger;
4905 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004906 };
4907
4908 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4909 auto parent = layerHandle->owner.promote();
4910
chaviw7206d492017-11-10 16:16:12 -08004911 if (parent == nullptr || parent->isPendingRemoval()) {
4912 ALOGE("captureLayers called with a removed parent");
4913 return NAME_NOT_FOUND;
4914 }
4915
Robert Carr578038f2018-03-09 12:25:24 -08004916 const int uid = IPCThreadState::self()->getCallingUid();
4917 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4918 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4919 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4920 return PERMISSION_DENIED;
4921 }
4922
chaviw7206d492017-11-10 16:16:12 -08004923 Rect crop(sourceCrop);
4924 if (sourceCrop.width() <= 0) {
4925 crop.left = 0;
4926 crop.right = parent->getCurrentState().active.w;
4927 }
4928
4929 if (sourceCrop.height() <= 0) {
4930 crop.top = 0;
4931 crop.bottom = parent->getCurrentState().active.h;
4932 }
4933
4934 int32_t reqWidth = crop.width() * frameScale;
4935 int32_t reqHeight = crop.height() * frameScale;
4936
Robert Carr578038f2018-03-09 12:25:24 -08004937 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004938
Robert Carr578038f2018-03-09 12:25:24 -08004939 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004940 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4941 if (!layer->isVisible()) {
4942 return;
Robert Carr578038f2018-03-09 12:25:24 -08004943 } else if (childrenOnly && layer == parent.get()) {
4944 return;
chaviwa76b2712017-09-20 12:02:26 -07004945 }
4946 visitor(layer);
4947 });
4948 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004949 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004950}
4951
4952status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4953 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004954 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004955 bool useIdentityTransform) {
4956 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004957
chaviwa76b2712017-09-20 12:02:26 -07004958 renderArea.updateDimensions();
4959
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004960 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4961 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4962 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4963 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004964
4965 // This mutex protects syncFd and captureResult for communication of the return values from the
4966 // main thread back to this Binder thread
4967 std::mutex captureMutex;
4968 std::condition_variable captureCondition;
4969 std::unique_lock<std::mutex> captureLock(captureMutex);
4970 int syncFd = -1;
4971 std::optional<status_t> captureResult;
4972
Robert Carr03480e22018-01-04 16:02:06 -08004973 const int uid = IPCThreadState::self()->getCallingUid();
4974 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4975
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004976 sp<LambdaMessage> message = new LambdaMessage([&]() {
4977 // If there is a refresh pending, bug out early and tell the binder thread to try again
4978 // after the refresh.
4979 if (mRefreshPending) {
4980 ATRACE_NAME("Skipping screenshot for now");
4981 std::unique_lock<std::mutex> captureLock(captureMutex);
4982 captureResult = std::make_optional<status_t>(EAGAIN);
4983 captureCondition.notify_one();
4984 return;
4985 }
4986
4987 status_t result = NO_ERROR;
4988 int fd = -1;
4989 {
4990 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004991 renderArea.render([&]() {
4992 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4993 useIdentityTransform, forSystem, &fd);
4994 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004995 }
4996
4997 {
4998 std::unique_lock<std::mutex> captureLock(captureMutex);
4999 syncFd = fd;
5000 captureResult = std::make_optional<status_t>(result);
5001 captureCondition.notify_one();
5002 }
5003 });
5004
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005005 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005006 if (result == NO_ERROR) {
5007 captureCondition.wait(captureLock, [&]() { return captureResult; });
5008 while (*captureResult == EAGAIN) {
5009 captureResult.reset();
5010 result = postMessageAsync(message);
5011 if (result != NO_ERROR) {
5012 return result;
5013 }
5014 captureCondition.wait(captureLock, [&]() { return captureResult; });
5015 }
5016 result = *captureResult;
5017 }
5018
5019 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005020 sync_wait(syncFd, -1);
5021 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005022 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005023
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005024 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005025}
5026
chaviwa76b2712017-09-20 12:02:26 -07005027void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
5028 TraverseLayersFunction traverseLayers, bool yswap,
5029 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005030 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005031
Lloyd Pique144e1162017-12-20 16:44:52 -08005032 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005033
5034 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005035 const auto raWidth = renderArea.getWidth();
5036 const auto raHeight = renderArea.getHeight();
5037
5038 const auto reqWidth = renderArea.getReqWidth();
5039 const auto reqHeight = renderArea.getReqHeight();
5040 Rect sourceCrop = renderArea.getSourceCrop();
5041
5042 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5043 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005044
Dan Stozac1879002014-05-22 15:59:05 -07005045 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005046 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005047 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005048 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07005049 }
5050
5051 // ensure that sourceCrop is inside screen
5052 if (sourceCrop.left < 0) {
5053 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5054 }
chaviwa76b2712017-09-20 12:02:26 -07005055 if (sourceCrop.right > raWidth) {
5056 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005057 }
5058 if (sourceCrop.top < 0) {
5059 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5060 }
chaviwa76b2712017-09-20 12:02:26 -07005061 if (sourceCrop.bottom > raHeight) {
5062 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005063 }
5064
Chia-I Wu36574d92018-05-16 10:54:36 -07005065 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5066 engine.setOutputDataSpace(Dataspace::SRGB);
5067 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005068
Mathias Agopian180f10d2013-04-10 22:55:41 -07005069 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005070 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005071
5072 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005073 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
5074 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07005075 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005076
chaviw50da5042018-04-09 13:49:37 -07005077 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005078 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005079 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005080
chaviwa76b2712017-09-20 12:02:26 -07005081 traverseLayers([&](Layer* layer) {
5082 if (filtering) layer->setFiltering(true);
bohu21566132018-03-27 14:36:34 -07005083 layer->draw(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005084 if (filtering) layer->setFiltering(false);
5085 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005086}
5087
chaviwa76b2712017-09-20 12:02:26 -07005088status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5089 TraverseLayersFunction traverseLayers,
5090 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005091 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005092 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005093 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005094 ATRACE_CALL();
5095
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005096 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005097
5098 traverseLayers([&](Layer* layer) {
5099 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5100 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005101
Robert Carr03480e22018-01-04 16:02:06 -08005102 // We allow the system server to take screenshots of secure layers for
5103 // use in situations like the Screen-rotation animation and place
5104 // the impetus on WindowManager to not persist them.
5105 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005106 ALOGW("FB is protected: PERMISSION_DENIED");
5107 return PERMISSION_DENIED;
5108 }
5109
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005110 // this binds the given EGLImage as a framebuffer for the
5111 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005112 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005113 if (bufferBond.getStatus() != NO_ERROR) {
5114 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005115 return INVALID_OPERATION;
5116 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005117
Dan Stozaabcda352017-06-01 14:37:39 -07005118 // this will in fact render into our dequeued buffer
5119 // via an FBO, which means we didn't have to create
5120 // an EGLSurface and therefore we're not
5121 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005122 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005123
Dan Stozaabcda352017-06-01 14:37:39 -07005124 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005125 getRenderEngine().finish();
5126 *outSyncFd = -1;
5127
chaviwa76b2712017-09-20 12:02:26 -07005128 const auto reqWidth = renderArea.getReqWidth();
5129 const auto reqHeight = renderArea.getReqHeight();
5130
Dan Stozaabcda352017-06-01 14:37:39 -07005131 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5132 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005133 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005134 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005135 } else {
5136 base::unique_fd syncFd = getRenderEngine().flush();
5137 if (syncFd < 0) {
5138 getRenderEngine().finish();
5139 }
5140 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005141 }
5142
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005143 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005144}
5145
Mathias Agopiand5556842013-09-19 17:08:37 -07005146void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005147 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005148 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005149 for (size_t y = 0; y < h; y++) {
5150 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5151 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005152 if (p[x] != 0xFF000000) return;
5153 }
5154 }
chaviwa76b2712017-09-20 12:02:26 -07005155 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005156
Robert Carr2047fae2016-11-28 14:09:09 -08005157 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005158 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005159 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005160 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5161 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5162 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5163 static_cast<float>(state.color.a));
5164 i++;
5165 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005166 }
5167}
5168
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005169// ---------------------------------------------------------------------------
5170
Dan Stoza412903f2017-04-27 13:42:17 -07005171void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5172 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005173}
5174
Dan Stoza412903f2017-04-27 13:42:17 -07005175void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5176 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005177}
5178
chaviwa76b2712017-09-20 12:02:26 -07005179void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
5180 int32_t maxLayerZ,
5181 const LayerVector::Visitor& visitor) {
5182 // We loop through the first level of layers without traversing,
5183 // as we need to interpret min/max layer Z in the top level Z space.
5184 for (const auto& layer : mDrawingState.layersSortedByZ) {
5185 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5186 continue;
5187 }
5188 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005189 // relative layers are traversed in Layer::traverseInZOrder
5190 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005191 continue;
5192 }
5193 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005194 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5195 return;
5196 }
chaviwa76b2712017-09-20 12:02:26 -07005197 if (!layer->isVisible()) {
5198 return;
5199 }
5200 visitor(layer);
5201 });
5202 }
5203}
5204
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005205}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005206
Chia-I Wu30505fb2018-03-26 16:20:31 -07005207
Mathias Agopian3f844832013-08-07 21:24:32 -07005208#if defined(__gl_h_)
5209#error "don't include gl/gl.h in this file"
5210#endif
5211
5212#if defined(__gl2_h_)
5213#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005214#endif