blob: 40a7460855c5d754f534ab3b345bfb40ab06d74c [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060040#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070041#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070042#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043
Jamie Gennis1a4d8832012-08-02 20:11:05 -070044#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070045#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080047#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080048#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070049
50#include <ui/GraphicBufferAllocator.h>
51#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080053
Mathias Agopiancde87a32012-09-13 14:09:01 -070054#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080055#include <utils/String8.h>
56#include <utils/String16.h>
57#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070058#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080059#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060
Mathias Agopian921e6ac2012-07-23 23:11:29 -070061#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070062#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063
Robert Carr578038f2018-03-09 12:25:24 -080064#include "BufferLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020065#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080066#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020067#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080068#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080069#include "DdmConnection.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070070#include "DispSync.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "DisplayDevice.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070072#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080073#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
Robert Carr578038f2018-03-09 12:25:24 -080078#include "clz.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Steven Thomasb02664d2017-07-26 18:48:28 -070080#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070081#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070082#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070083#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084
Mathias Agopianff2ed702013-09-01 21:36:12 -070085#include "Effects/Daltonizer.h"
86
Mathias Agopian875d8e12013-06-07 15:35:48 -070087#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070088#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070089
Jiyong Park4b20c2e2017-01-14 19:45:11 +090090#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090091#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090092
chaviw1d044282017-09-27 12:19:28 -070093#include <layerproto/LayerProtoParser.h>
94
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080095#define DISPLAY_COUNT 1
96
Mathias Agopianfee2b462013-07-03 12:34:01 -070097/*
98 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
99 * black pixels.
100 */
101#define DEBUG_SCREENSHOTS false
102
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800103namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700104
Jaesoo Lee43518572017-01-23 19:03:16 +0900105using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900106using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700107using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700108using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700109using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700110using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900111
Steven Thomasb02664d2017-07-26 18:48:28 -0700112namespace {
113class ConditionalLock {
114public:
115 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
116 if (lock) {
117 mMutex.lock();
118 }
119 }
120 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
121private:
122 Mutex& mMutex;
123 bool mLocked;
124};
125} // namespace anonymous
126
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800127// ---------------------------------------------------------------------------
128
Mathias Agopian99b49842011-06-27 16:05:52 -0700129const String16 sHardwareTest("android.permission.HARDWARE_TEST");
130const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
131const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
132const String16 sDump("android.permission.DUMP");
133
134// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800135int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
136int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700137int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700138bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800139uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800140bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800141bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800142int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800143// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600144bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700145
Kalle Raitaa099a242017-01-11 11:17:29 -0800146
147std::string getHwcServiceName() {
148 char value[PROPERTY_VALUE_MAX] = {};
149 property_get("debug.sf.hwc_service_name", value, "default");
150 ALOGI("Using HWComposer service: '%s'", value);
151 return std::string(value);
152}
153
154bool useTrebleTestingOverride() {
155 char value[PROPERTY_VALUE_MAX] = {};
156 property_get("debug.sf.treble_testing_override", value, "false");
157 ALOGI("Treble testing override: '%s'", value);
158 return std::string(value) == "true";
159}
160
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800161DisplayColorSetting toDisplayColorSetting(int value) {
162 switch(value) {
163 case 0:
164 return DisplayColorSetting::MANAGED;
165 case 1:
166 return DisplayColorSetting::UNMANAGED;
167 case 2:
168 return DisplayColorSetting::ENHANCED;
169 default:
170 return DisplayColorSetting::MANAGED;
171 }
172}
173
174std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
175 switch(displayColorSetting) {
176 case DisplayColorSetting::MANAGED:
177 return std::string("Natural Mode");
178 case DisplayColorSetting::UNMANAGED:
179 return std::string("Saturated Mode");
180 case DisplayColorSetting::ENHANCED:
181 return std::string("Auto Color Mode");
182 }
183 return std::string("Unknown Display Color Setting");
184}
185
Lloyd Pique99d3da52018-01-22 17:48:03 -0800186NativeWindowSurface::~NativeWindowSurface() = default;
187
188namespace impl {
189
190class NativeWindowSurface final : public android::NativeWindowSurface {
191public:
192 static std::unique_ptr<android::NativeWindowSurface> create(
193 const sp<IGraphicBufferProducer>& producer) {
194 return std::make_unique<NativeWindowSurface>(producer);
195 }
196
197 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
198 : surface(new Surface(producer, false)) {}
199
200 ~NativeWindowSurface() override = default;
201
202private:
203 sp<ANativeWindow> getNativeWindow() const override { return surface; }
204
205 void preallocateBuffers() override { surface->allocateBuffers(); }
206
207 sp<Surface> surface;
208};
209
210} // namespace impl
211
David Sodmanbc815282017-11-05 18:57:52 -0800212SurfaceFlingerBE::SurfaceFlingerBE()
213 : mHwcServiceName(getHwcServiceName()),
214 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800215 mFrameBuckets(),
216 mTotalTime(0),
217 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800218 mComposerSequenceId(0) {
219}
220
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800221SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800222 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800223 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700224 mTransactionPending(false),
225 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700226 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700227 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700228 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800229 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800230 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800231 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800232 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800233 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800234 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700235 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700236 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700237 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700238 mDebugInSwapBuffers(0),
239 mLastSwapBufferTime(0),
240 mDebugInTransaction(0),
241 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700242 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700243 mForceFullDamage(false),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000244 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700245 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700246 mHWVsyncAvailable(false),
Romain Guya9638732017-06-01 12:05:21 -0700247 mHasColorMatrix(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800248 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800249 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700250 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800251 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800252 mCreateBufferQueue(&BufferQueue::createBufferQueue),
253 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800254
255SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800256 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800257
258 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
259 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
260
261 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
262 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
263
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800264 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
265 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800266
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700267 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
268 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
269
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700270 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
271 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
272
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800273 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
274 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
275
Steven Thomas050b2c82017-03-06 11:45:16 -0800276 // Vr flinger is only enabled on Daydream ready devices.
277 useVrFlinger = getBool< ISurfaceFlingerConfigs,
278 &ISurfaceFlingerConfigs::useVrFlinger>(false);
279
Fabien Sanglard1971b632017-03-10 14:50:03 -0800280 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
281 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
282
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600283 hasWideColorDisplay =
284 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
285
David Sodman99974d22017-11-28 12:04:33 -0800286 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700287
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800288 // debugging stuff...
289 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700290
Mathias Agopianb4b17302013-03-20 18:36:41 -0700291 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700292 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700293
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800294 property_get("debug.sf.showupdates", value, "0");
295 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700296
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700297 property_get("debug.sf.ddms", value, "0");
298 mDebugDDMS = atoi(value);
299 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700300 if (!startDdmConnection()) {
301 // start failed, and DDMS debugging not enabled
302 mDebugDDMS = 0;
303 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700304 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700305 ALOGI_IF(mDebugRegion, "showupdates enabled");
306 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700307
308 property_get("debug.sf.disable_backpressure", value, "0");
309 mPropagateBackpressure = !atoi(value);
310 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700311
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800312 property_get("debug.sf.enable_hwc_vds", value, "0");
313 mUseHwcVirtualDisplays = atoi(value);
314 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800315
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800316 property_get("ro.sf.disable_triple_buffer", value, "1");
317 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800318 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700319
Dan Stoza0a0158c2018-03-16 13:38:54 -0700320 // TODO (b/74616334): Reduce the default value once we isolate the leak
321 const size_t defaultListSize = 4 * MAX_LAYERS;
322 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
323 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
324
Dan Stoza84d619e2018-03-28 17:07:36 -0700325 property_get("debug.sf.early_phase_offset_ns", value, "0");
326 const int earlyWakeupOffsetOffsetNs = atoi(value);
327 ALOGI_IF(earlyWakeupOffsetOffsetNs != 0, "Enabling separate early offset");
328 mVsyncModulator.setPhaseOffsets(sfVsyncPhaseOffsetNs - earlyWakeupOffsetOffsetNs,
329 sfVsyncPhaseOffsetNs);
330
Romain Guy11d63f42017-07-20 12:47:14 -0700331 // We should be reading 'persist.sys.sf.color_saturation' here
332 // but since /data may be encrypted, we need to wait until after vold
333 // comes online to attempt to read the property. The property is
334 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800335
336 if (useTrebleTestingOverride()) {
337 // Without the override SurfaceFlinger cannot connect to HIDL
338 // services that are not listed in the manifests. Considered
339 // deriving the setting from the set service name, but it
340 // would be brittle if the name that's not 'default' is used
341 // for production purposes later on.
342 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
343 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800344}
345
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800346void SurfaceFlinger::onFirstRef()
347{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800348 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800349}
350
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800351SurfaceFlinger::~SurfaceFlinger()
352{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800353}
354
Dan Stozac7014012014-02-14 15:03:43 -0800355void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800356{
357 // the window manager died on us. prepare its eulogy.
358
Andy McFadden13a082e2012-08-24 10:16:42 -0700359 // restore initial conditions (default device unblank, etc)
360 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800361
362 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700363 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800364}
365
Robert Carr1db73f62016-12-21 12:58:51 -0800366static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700367 status_t err = client->initCheck();
368 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800369 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800370 }
Robert Carr1db73f62016-12-21 12:58:51 -0800371 return nullptr;
372}
373
374sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
375 return initClient(new Client(this));
376}
377
378sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
379 const sp<IGraphicBufferProducer>& gbp) {
380 if (authenticateSurfaceTexture(gbp) == false) {
381 return nullptr;
382 }
383 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
384 if (layer == nullptr) {
385 return nullptr;
386 }
387
388 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800389}
390
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700391sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
392 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700393{
394 class DisplayToken : public BBinder {
395 sp<SurfaceFlinger> flinger;
396 virtual ~DisplayToken() {
397 // no more references, this display must be terminated
398 Mutex::Autolock _l(flinger->mStateLock);
399 flinger->mCurrentState.displays.removeItem(this);
400 flinger->setTransactionFlags(eDisplayTransactionNeeded);
401 }
402 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700403 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700404 : flinger(flinger) {
405 }
406 };
407
408 sp<BBinder> token = new DisplayToken(this);
409
410 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700411 DisplayDeviceState info;
412 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700413 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700414 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700415 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800416 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700417 return token;
418}
419
Jesse Hall6c913be2013-08-08 12:15:49 -0700420void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
421 Mutex::Autolock _l(mStateLock);
422
423 ssize_t idx = mCurrentState.displays.indexOfKey(display);
424 if (idx < 0) {
425 ALOGW("destroyDisplay: invalid display token");
426 return;
427 }
428
429 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700430 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700431 ALOGE("destroyDisplay called for non-virtual display");
432 return;
433 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700434 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700435 mCurrentState.displays.removeItemsAt(idx);
436 setTransactionFlags(eDisplayTransactionNeeded);
437}
438
Mathias Agopiane57f2922012-08-09 16:29:12 -0700439sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700440 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700441 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800442 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700443 }
Jesse Hall692c7232012-11-08 15:41:56 -0800444 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700445}
446
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800447void SurfaceFlinger::bootFinished()
448{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700449 if (mStartPropertySetThread->join() != NO_ERROR) {
450 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800451 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800452 const nsecs_t now = systemTime();
453 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000454 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700455
456 // wait patiently for the window manager death
457 const String16 name("window");
458 sp<IBinder> window(defaultServiceManager()->getService(name));
459 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700460 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700461 }
462
Steven Thomas050b2c82017-03-06 11:45:16 -0800463 if (mVrFlinger) {
464 mVrFlinger->OnBootFinished();
465 }
466
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700467 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700468 // formerly we would just kill the process, but we now ask it to exit so it
469 // can choose where to stop the animation.
470 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700471
472 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
473 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
474 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700475
Thierry Strudel2924d012017-08-14 15:19:37 -0700476 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700477 readPersistentProperties();
478 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700479 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800480}
481
Mathias Agopian3f844832013-08-07 21:24:32 -0700482void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700483 class MessageDestroyGLTexture : public MessageBase {
Lloyd Pique144e1162017-12-20 16:44:52 -0800484 RE::RenderEngine& engine;
Mathias Agopian3f844832013-08-07 21:24:32 -0700485 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700486 public:
Lloyd Pique144e1162017-12-20 16:44:52 -0800487 MessageDestroyGLTexture(RE::RenderEngine& engine, uint32_t texture)
488 : engine(engine), texture(texture) {}
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700489 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700490 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700491 return true;
492 }
493 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700494 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700495}
496
Lloyd Piquee83f9312018-02-01 12:53:17 -0800497class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700498public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700499 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000500 const char* name) :
501 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700502 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700503 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000504 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
505 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700506 mDispSync(dispSync),
507 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700508 mVsyncMutex(),
509 mPhaseOffset(phaseOffset),
510 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700511
Lloyd Piquee83f9312018-02-01 12:53:17 -0800512 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700513
Lloyd Piquee83f9312018-02-01 12:53:17 -0800514 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700515 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700516 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000517 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700518 static_cast<DispSync::Callback*>(this));
519 if (err != NO_ERROR) {
520 ALOGE("error registering vsync callback: %s (%d)",
521 strerror(-err), err);
522 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700523 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700524 } else {
525 status_t err = mDispSync->removeEventListener(
526 static_cast<DispSync::Callback*>(this));
527 if (err != NO_ERROR) {
528 ALOGE("error unregistering vsync callback: %s (%d)",
529 strerror(-err), err);
530 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700531 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700532 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700533 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700534 }
535
Lloyd Piquee83f9312018-02-01 12:53:17 -0800536 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700537 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700538 mCallback = callback;
539 }
540
Lloyd Piquee83f9312018-02-01 12:53:17 -0800541 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700542 Mutex::Autolock lock(mVsyncMutex);
543
544 // Normalize phaseOffset to [0, period)
545 auto period = mDispSync->getPeriod();
546 phaseOffset %= period;
547 if (phaseOffset < 0) {
548 // If we're here, then phaseOffset is in (-period, 0). After this
549 // operation, it will be in (0, period)
550 phaseOffset += period;
551 }
552 mPhaseOffset = phaseOffset;
553
554 // If we're not enabled, we don't need to mess with the listeners
555 if (!mEnabled) {
556 return;
557 }
558
Dan Stoza84d619e2018-03-28 17:07:36 -0700559 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
560 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700561 if (err != NO_ERROR) {
Dan Stoza84d619e2018-03-28 17:07:36 -0700562 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700563 strerror(-err), err);
564 }
565 }
566
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700567private:
568 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800569 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700570 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700571 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700572 callback = mCallback;
573
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700574 if (mTraceVsync) {
575 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700576 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700577 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700578 }
579
Peiyong Lin566a3b42018-01-09 18:22:43 -0800580 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700581 callback->onVSyncEvent(when);
582 }
583 }
584
Tim Murray4a4e4a22016-04-19 16:29:23 +0000585 const char* const mName;
586
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700587 int mValue;
588
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700589 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700590 const String8 mVsyncOnLabel;
591 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700592
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700593 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700594
595 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800596 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700597
598 Mutex mVsyncMutex; // Protects the following
599 nsecs_t mPhaseOffset;
600 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700601};
602
Lloyd Piquee83f9312018-02-01 12:53:17 -0800603class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700604public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800605 InjectVSyncSource() = default;
606 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700607
Lloyd Piquee83f9312018-02-01 12:53:17 -0800608 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700609 std::lock_guard<std::mutex> lock(mCallbackMutex);
610 mCallback = callback;
611 }
612
Lloyd Piquee83f9312018-02-01 12:53:17 -0800613 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700614 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700615 if (mCallback) {
616 mCallback->onVSyncEvent(when);
617 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700618 }
619
Lloyd Piquee83f9312018-02-01 12:53:17 -0800620 void setVSyncEnabled(bool) override {}
621 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700622
623private:
624 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800625 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700626};
627
Wei Wangf9b05ee2017-07-19 20:59:39 -0700628// Do not call property_set on main thread which will be blocked by init
629// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700630void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700631 ALOGI( "SurfaceFlinger's main thread ready to run. "
632 "Initializing graphics H/W...");
633
Thierry Strudel2924d012017-08-14 15:19:37 -0700634 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900635
Steven Thomasb02664d2017-07-26 18:48:28 -0700636 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800637
Steven Thomasb02664d2017-07-26 18:48:28 -0700638 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800639 mEventThreadSource =
640 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
641 true, "app");
642 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(), *this, false,
643 "appEventThread");
644 mSfEventThreadSource =
645 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
646 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800647
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800648 mSFEventThread = std::make_unique<impl::EventThread>(mSfEventThreadSource.get(), *this, true,
649 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800650 mEventQueue->setEventThread(mSFEventThread.get());
Dan Stoza84d619e2018-03-28 17:07:36 -0700651 mVsyncModulator.setEventThread(mSFEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800652
Steven Thomasb02664d2017-07-26 18:48:28 -0700653 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800654 getBE().mRenderEngine =
655 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
656 hasWideColorDisplay
657 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
658 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800659 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700660
661 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
662 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800663 getBE().mHwc.reset(
664 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700665 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800666 // Process any initial hotplug and resulting display changes.
667 processDisplayHotplugEventsLocked();
668 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
669 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800670
Lloyd Piquefcd86612017-12-14 17:15:36 -0800671 // make the default display GLContext current so that we can create textures
672 // when creating Layers (which may happens before we render something)
673 getDefaultDisplayDeviceLocked()->makeCurrent();
674
Steven Thomas050b2c82017-03-06 11:45:16 -0800675 if (useVrFlinger) {
676 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700677 // This callback is called from the vr flinger dispatch thread. We
678 // need to call signalTransaction(), which requires holding
679 // mStateLock when we're not on the main thread. Acquiring
680 // mStateLock from the vr flinger dispatch thread might trigger a
681 // deadlock in surface flinger (see b/66916578), so post a message
682 // to be handled on the main thread instead.
683 sp<LambdaMessage> message = new LambdaMessage([=]() {
684 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
685 mVrFlingerRequestsDisplay = requestDisplay;
686 signalTransaction();
687 });
688 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800689 };
David Sodman105b7dc2017-11-04 20:28:14 -0700690 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
691 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800692 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800693 if (!mVrFlinger) {
694 ALOGE("Failed to start vrflinger");
695 }
696 }
697
Lloyd Pique379adc12018-01-22 17:31:47 -0800698 mEventControlThread = std::make_unique<impl::EventControlThread>(
699 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700700
Mathias Agopian92a979a2012-08-02 18:32:23 -0700701 // initialize our drawing state
702 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700703
Andy McFadden13a082e2012-08-24 10:16:42 -0700704 // set initial conditions (e.g. unblank default device)
705 initializeDisplays();
706
David Sodmanbc815282017-11-05 18:57:52 -0800707 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700708
Wei Wangf9b05ee2017-07-19 20:59:39 -0700709 // Inform native graphics APIs whether the present timestamp is supported:
710 if (getHwComposer().hasCapability(
711 HWC2::Capability::PresentFenceIsNotReliable)) {
712 mStartPropertySetThread = new StartPropertySetThread(false);
713 } else {
714 mStartPropertySetThread = new StartPropertySetThread(true);
715 }
716
717 if (mStartPropertySetThread->Start() != NO_ERROR) {
718 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800719 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800720
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800721 mLegacySrgbSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(HWC_DISPLAY_PRIMARY,
722 Dataspace::SRGB_LINEAR);
723
Dan Stoza9e56aa02015-11-02 13:00:03 -0800724 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700725}
726
Romain Guy11d63f42017-07-20 12:47:14 -0700727void SurfaceFlinger::readPersistentProperties() {
728 char value[PROPERTY_VALUE_MAX];
729
730 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800731 mGlobalSaturationFactor = atof(value);
732 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100733
734 property_get("persist.sys.sf.native_mode", value, "0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800735 mDisplayColorSetting = toDisplayColorSetting(atoi(value));
736 ALOGV("Display Color Setting is set to %s.",
737 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Romain Guy11d63f42017-07-20 12:47:14 -0700738}
739
Mathias Agopiana67e4182012-06-19 17:26:12 -0700740void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800741 // Start boot animation service by setting a property mailbox
742 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700743 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800744 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700745 if (mStartPropertySetThread->join() != NO_ERROR) {
746 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800747 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700748}
749
Mathias Agopian875d8e12013-06-07 15:35:48 -0700750size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800751 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700752}
753
Mathias Agopian875d8e12013-06-07 15:35:48 -0700754size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800755 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700756}
757
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800758// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800759
Jamie Gennis582270d2011-08-17 18:19:00 -0700760bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800761 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800762 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800763 return authenticateSurfaceTextureLocked(bufferProducer);
764}
765
766bool SurfaceFlinger::authenticateSurfaceTextureLocked(
767 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800768 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800769 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800770}
771
Brian Anderson6b376712017-04-04 10:51:39 -0700772status_t SurfaceFlinger::getSupportedFrameTimestamps(
773 std::vector<FrameEvent>* outSupported) const {
774 *outSupported = {
775 FrameEvent::REQUESTED_PRESENT,
776 FrameEvent::ACQUIRE,
777 FrameEvent::LATCH,
778 FrameEvent::FIRST_REFRESH_START,
779 FrameEvent::LAST_REFRESH_START,
780 FrameEvent::GPU_COMPOSITION_DONE,
781 FrameEvent::DEQUEUE_READY,
782 FrameEvent::RELEASE,
783 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700784 ConditionalLock _l(mStateLock,
785 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700786 if (!getHwComposer().hasCapability(
787 HWC2::Capability::PresentFenceIsNotReliable)) {
788 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
789 }
790 return NO_ERROR;
791}
792
Dan Stoza7f7da322014-05-02 15:26:25 -0700793status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
794 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800795 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700796 return BAD_VALUE;
797 }
798
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500799 if (!display.get())
800 return NAME_NOT_FOUND;
801
Jesse Hall692c7232012-11-08 15:41:56 -0800802 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700803 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800804 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700805 type = i;
806 break;
807 }
808 }
809
810 if (type < 0) {
811 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700812 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700813
Mathias Agopian8b736f12012-08-13 17:54:26 -0700814 // TODO: Not sure if display density should handled by SF any longer
815 class Density {
816 static int getDensityFromProperty(char const* propName) {
817 char property[PROPERTY_VALUE_MAX];
818 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800819 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700820 density = atoi(property);
821 }
822 return density;
823 }
824 public:
825 static int getEmuDensity() {
826 return getDensityFromProperty("qemu.sf.lcd_density"); }
827 static int getBuildDensity() {
828 return getDensityFromProperty("ro.sf.lcd_density"); }
829 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700830
Dan Stoza7f7da322014-05-02 15:26:25 -0700831 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700832
Steven Thomas6d8110b2017-08-31 18:24:21 -0700833 ConditionalLock _l(mStateLock,
834 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800835 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700836 DisplayInfo info = DisplayInfo();
837
Dan Stoza9e56aa02015-11-02 13:00:03 -0800838 float xdpi = hwConfig->getDpiX();
839 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700840
841 if (type == DisplayDevice::DISPLAY_PRIMARY) {
842 // The density of the device is provided by a build property
843 float density = Density::getBuildDensity() / 160.0f;
844 if (density == 0) {
845 // the build doesn't provide a density -- this is wrong!
846 // use xdpi instead
847 ALOGE("ro.sf.lcd_density must be defined as a build property");
848 density = xdpi / 160.0f;
849 }
850 if (Density::getEmuDensity()) {
851 // if "qemu.sf.lcd_density" is specified, it overrides everything
852 xdpi = ydpi = density = Density::getEmuDensity();
853 density /= 160.0f;
854 }
855 info.density = density;
856
857 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700858 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800859 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700860 } else {
861 // TODO: where should this value come from?
862 static const int TV_DENSITY = 213;
863 info.density = TV_DENSITY / 160.0f;
864 info.orientation = 0;
865 }
866
Dan Stoza9e56aa02015-11-02 13:00:03 -0800867 info.w = hwConfig->getWidth();
868 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700869 info.xdpi = xdpi;
870 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800871 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900872 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800873
Andy McFadden91b2ca82014-06-13 14:04:23 -0700874 // This is how far in advance a buffer must be queued for
875 // presentation at a given time. If you want a buffer to appear
876 // on the screen at time N, you must submit the buffer before
877 // (N - presentationDeadline).
878 //
879 // Normally it's one full refresh period (to give SF a chance to
880 // latch the buffer), but this can be reduced by configuring a
881 // DispSync offset. Any additional delays introduced by the hardware
882 // composer or panel must be accounted for here.
883 //
884 // We add an additional 1ms to allow for processing time and
885 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800886 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800887 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700888
889 // All non-virtual displays are currently considered secure.
890 info.secure = true;
891
Michael Wright28f24d02016-07-12 13:30:53 -0700892 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700893 }
894
Dan Stoza7f7da322014-05-02 15:26:25 -0700895 return NO_ERROR;
896}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700897
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800898status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700899 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800900 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700901 return BAD_VALUE;
902 }
903
904 // FIXME for now we always return stats for the primary display
905 memset(stats, 0, sizeof(*stats));
906 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
907 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
908 return NO_ERROR;
909}
910
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700911int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800912 if (display == nullptr) {
913 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800914 return BAD_VALUE;
915 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700916
917 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800918 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700919 return device->getActiveConfig();
920 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700921
Dan Stoza24a42e92015-03-09 10:04:11 -0700922 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700923}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700924
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700925void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
926 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
927 this);
928 int32_t type = hw->getDisplayType();
929 int currentMode = hw->getActiveConfig();
930
931 if (mode == currentMode) {
932 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
933 return;
934 }
935
936 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
937 ALOGW("Trying to set config for virtual display");
938 return;
939 }
940
941 hw->setActiveConfig(mode);
942 getHwComposer().setActiveConfig(type, mode);
943}
944
945status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
946 class MessageSetActiveConfig: public MessageBase {
947 SurfaceFlinger& mFlinger;
948 sp<IBinder> mDisplay;
949 int mMode;
950 public:
951 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
952 int mode) :
953 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
954 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700955 Vector<DisplayInfo> configs;
956 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700957 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700958 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700959 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700960 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700961 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700962 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800963 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700964 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700965 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700966 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
967 ALOGW("Attempt to set active config = %d for virtual display",
968 mMode);
969 } else {
970 mFlinger.setActiveConfigInternal(hw, mMode);
971 }
972 return true;
973 }
974 };
975 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
976 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700977 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700978}
Michael Wright28f24d02016-07-12 13:30:53 -0700979status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -0700980 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700981 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
982 return BAD_VALUE;
983 }
984
985 if (!display.get()) {
986 return NAME_NOT_FOUND;
987 }
988
989 int32_t type = NAME_NOT_FOUND;
990 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
991 if (display == mBuiltinDisplays[i]) {
992 type = i;
993 break;
994 }
995 }
996
997 if (type < 0) {
998 return type;
999 }
1000
Peiyong Lina52f0292018-03-14 17:26:31 -07001001 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001002 {
1003 ConditionalLock _l(mStateLock,
1004 std::this_thread::get_id() != mMainThreadId);
1005 modes = getHwComposer().getColorModes(type);
1006 }
Michael Wright28f24d02016-07-12 13:30:53 -07001007 outColorModes->clear();
1008 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1009
1010 return NO_ERROR;
1011}
1012
Peiyong Lina52f0292018-03-14 17:26:31 -07001013ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001014 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -07001015 if (device != nullptr) {
1016 return device->getActiveColorMode();
1017 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001018 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001019}
1020
1021void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001022 ColorMode mode, Dataspace dataSpace) {
Michael Wright28f24d02016-07-12 13:30:53 -07001023 int32_t type = hw->getDisplayType();
Peiyong Lina52f0292018-03-14 17:26:31 -07001024 ColorMode currentMode = hw->getActiveColorMode();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001025 Dataspace currentDataSpace = hw->getCompositionDataSpace();
Peiyong Lin38e9a562018-04-10 16:24:20 -07001026 RenderIntent currentRenderIntent = hw->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001027
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001028 // Natural Mode means it's color managed and the color must be right,
1029 // thus we pick RenderIntent::COLORIMETRIC as render intent.
1030 // Native Mode means the display is not color managed, and whichever
1031 // render intent is picked doesn't matter, thus return
1032 // RenderIntent::COLORIMETRIC as default here.
1033 RenderIntent renderIntent = RenderIntent::COLORIMETRIC;
1034
1035 // In Auto Color Mode, we want to strech to panel color space, right now
1036 // only the built-in display supports it.
1037 if (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
1038 mBuiltinDisplaySupportsEnhance &&
1039 hw->getDisplayType() == DisplayDevice::DISPLAY_PRIMARY) {
1040 renderIntent = RenderIntent::ENHANCE;
1041 }
Peiyong Lin38e9a562018-04-10 16:24:20 -07001042
1043 if (mode == currentMode && dataSpace == currentDataSpace &&
1044 renderIntent == currentRenderIntent) {
1045 return;
1046 }
1047
1048 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1049 ALOGW("Trying to set config for virtual display");
1050 return;
1051 }
1052
1053 hw->setActiveColorMode(mode);
1054 hw->setCompositionDataSpace(dataSpace);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001055 hw->setActiveRenderIntent(renderIntent);
1056 getHwComposer().setActiveColorMode(type, mode, renderIntent);
1057
1058 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
1059 decodeColorMode(mode).c_str(), mode,
1060 decodeRenderIntent(renderIntent).c_str(), renderIntent,
1061 hw->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001062}
1063
1064
1065status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001066 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -07001067 class MessageSetActiveColorMode: public MessageBase {
1068 SurfaceFlinger& mFlinger;
1069 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -07001070 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001071 public:
1072 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -07001073 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -07001074 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1075 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -07001076 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001077 mFlinger.getDisplayColorModes(mDisplay, &modes);
1078 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -07001079 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001080 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1081 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001082 return true;
1083 }
1084 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1085 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001086 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1087 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001088 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001089 ALOGW("Attempt to set active color mode %s %d for virtual display",
1090 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001091 } else {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001092 mFlinger.setActiveColorModeInternal(hw, mMode, Dataspace::UNKNOWN);
Michael Wright28f24d02016-07-12 13:30:53 -07001093 }
1094 return true;
1095 }
1096 };
1097 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1098 postMessageSync(msg);
1099 return NO_ERROR;
1100}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001101
Svetoslavd85084b2014-03-20 10:28:31 -07001102status_t SurfaceFlinger::clearAnimationFrameStats() {
1103 Mutex::Autolock _l(mStateLock);
1104 mAnimFrameTracker.clearStats();
1105 return NO_ERROR;
1106}
1107
1108status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1109 Mutex::Autolock _l(mStateLock);
1110 mAnimFrameTracker.getStats(outStats);
1111 return NO_ERROR;
1112}
1113
Dan Stozac4f471e2016-03-24 09:31:08 -07001114status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1115 HdrCapabilities* outCapabilities) const {
1116 Mutex::Autolock _l(mStateLock);
1117
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001118 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001119 if (displayDevice == nullptr) {
1120 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1121 return BAD_VALUE;
1122 }
1123
Peiyong Lin62665892018-04-16 11:07:44 -07001124 HdrCapabilities capabilities;
1125 int status = getBE().mHwc->getHdrCapabilities(
1126 displayDevice->getHwcDisplayId(), &capabilities);
1127 if (status == NO_ERROR) {
1128 if (displayDevice->hasWideColorGamut() &&
1129 !displayDevice->hasHDR10Support()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001130 // insert HDR10 as we will force client composition for HDR10
1131 // layers
Peiyong Lin62665892018-04-16 11:07:44 -07001132 std::vector<Hdr> types = capabilities.getSupportedHdrTypes();
1133 types.push_back(Hdr::HDR10);
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001134
1135 *outCapabilities = HdrCapabilities(types,
Peiyong Lin62665892018-04-16 11:07:44 -07001136 capabilities.getDesiredMaxLuminance(),
1137 capabilities.getDesiredMaxAverageLuminance(),
1138 capabilities.getDesiredMinLuminance());
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001139 } else {
Peiyong Lin62665892018-04-16 11:07:44 -07001140 *outCapabilities = std::move(capabilities);
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001141 }
Dan Stozac4f471e2016-03-24 09:31:08 -07001142 } else {
1143 return BAD_VALUE;
1144 }
1145
1146 return NO_ERROR;
1147}
1148
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001149status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001150 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1151 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001152
Chia-I Wu90f669f2017-10-05 14:24:41 -07001153 if (mInjectVSyncs == enable) {
1154 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001155 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001156
1157 if (enable) {
1158 ALOGV("VSync Injections enabled");
1159 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001160 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique0fcde1b2017-12-20 16:50:21 -08001161 mInjectorEventThread =
1162 std::make_unique<impl::EventThread>(mVSyncInjector.get(), *this, false,
1163 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001164 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001165 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001166 } else {
1167 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001168 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001169 }
1170
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001171 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001172 });
1173 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001174 return NO_ERROR;
1175}
1176
1177status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001178 Mutex::Autolock _l(mStateLock);
1179
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001180 if (!mInjectVSyncs) {
1181 ALOGE("VSync Injections not enabled");
1182 return BAD_VALUE;
1183 }
1184 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1185 ALOGV("Injecting VSync inside SurfaceFlinger");
1186 mVSyncInjector->onInjectSyncEvent(when);
1187 }
1188 return NO_ERROR;
1189}
1190
Lloyd Pique755e3192018-01-31 16:46:15 -08001191status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1192 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001193 IPCThreadState* ipc = IPCThreadState::self();
1194 const int pid = ipc->getCallingPid();
1195 const int uid = ipc->getCallingUid();
1196 if ((uid != AID_SHELL) &&
1197 !PermissionCache::checkPermission(sDump, pid, uid)) {
1198 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1199 return PERMISSION_DENIED;
1200 }
1201
1202 // Try to acquire a lock for 1s, fail gracefully
1203 const status_t err = mStateLock.timedLock(s2ns(1));
1204 const bool locked = (err == NO_ERROR);
1205 if (!locked) {
1206 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1207 return TIMED_OUT;
1208 }
1209
1210 outLayers->clear();
1211 mCurrentState.traverseInZOrder([&](Layer* layer) {
1212 outLayers->push_back(layer->getLayerDebugInfo());
1213 });
1214
1215 mStateLock.unlock();
1216 return NO_ERROR;
1217}
1218
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001219// ----------------------------------------------------------------------------
1220
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001221sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1222 ISurfaceComposer::VsyncSource vsyncSource) {
1223 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1224 return mSFEventThread->createEventConnection();
1225 } else {
1226 return mEventThread->createEventConnection();
1227 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001228}
1229
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001230// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001231
1232void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001233 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001234}
1235
1236void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001237 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001238}
1239
1240void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001241 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001242}
1243
1244void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001245 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001246 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001247}
1248
1249status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001250 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001251 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001252}
1253
1254status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001255 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001256 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001257 if (res == NO_ERROR) {
1258 msg->wait();
1259 }
1260 return res;
1261}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001262
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001263void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001264 do {
1265 waitForEvent();
1266 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001267}
1268
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001269void SurfaceFlinger::enableHardwareVsync() {
1270 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001271 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001272 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001273 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1274 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001275 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001276 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001277}
1278
Jesse Hall948fe0c2013-10-14 12:56:09 -07001279void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001280 Mutex::Autolock _l(mHWVsyncLock);
1281
Jesse Hall948fe0c2013-10-14 12:56:09 -07001282 if (makeAvailable) {
1283 mHWVsyncAvailable = true;
1284 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001285 // Hardware vsync is not currently available, so abort the resync
1286 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001287 return;
1288 }
1289
David Sodman105b7dc2017-11-04 20:28:14 -07001290 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001291 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001292
1293 mPrimaryDispSync.reset();
1294 mPrimaryDispSync.setPeriod(period);
1295
1296 if (!mPrimaryHWVsyncEnabled) {
1297 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001298 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1299 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001300 mPrimaryHWVsyncEnabled = true;
1301 }
1302}
1303
Jesse Hall948fe0c2013-10-14 12:56:09 -07001304void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001305 Mutex::Autolock _l(mHWVsyncLock);
1306 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001307 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1308 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001309 mPrimaryDispSync.endResync();
1310 mPrimaryHWVsyncEnabled = false;
1311 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001312 if (makeUnavailable) {
1313 mHWVsyncAvailable = false;
1314 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001315}
1316
Tim Murray4a4e4a22016-04-19 16:29:23 +00001317void SurfaceFlinger::resyncWithRateLimit() {
1318 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001319
1320 // No explicit locking is needed here since EventThread holds a lock while calling this method
1321 static nsecs_t sLastResyncAttempted = 0;
1322 const nsecs_t now = systemTime();
1323 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001324 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001325 }
Dan Stoza57164302017-05-08 14:03:54 -07001326 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001327}
1328
Steven Thomasb02664d2017-07-26 18:48:28 -07001329void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1330 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001331 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001332 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001333 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001334 return;
1335 }
1336
1337 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001338 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001339 return;
1340 }
1341
Jamie Gennisd1700752013-10-14 12:22:52 -07001342 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001343
Jamie Gennisd1700752013-10-14 12:22:52 -07001344 { // Scope for the lock
1345 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001346 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001347 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001348 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001349 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001350
1351 if (needsHwVsync) {
1352 enableHardwareVsync();
1353 } else {
1354 disableHardwareVsync(false);
1355 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001356}
1357
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001358void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001359 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1360 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001361}
1362
Lloyd Pique715a2c12017-12-14 17:18:08 -08001363void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1364 HWC2::Connection connection) {
1365 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1366 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001367
Lloyd Piqueba04e622017-12-14 17:11:26 -08001368 // Ignore events that do not have the right sequenceId.
1369 if (sequenceId != getBE().mComposerSequenceId) {
1370 return;
1371 }
1372
Steven Thomasb02664d2017-07-26 18:48:28 -07001373 // Only lock if we're not on the main thread. This function is normally
1374 // called on a hwbinder thread, but for the primary display it's called on
1375 // the main thread with the state lock already held, so don't attempt to
1376 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001377 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001378
Lloyd Pique715a2c12017-12-14 17:18:08 -08001379 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001380
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001381 if (std::this_thread::get_id() == mMainThreadId) {
1382 // Process all pending hot plug events immediately if we are on the main thread.
1383 processDisplayHotplugEventsLocked();
1384 }
1385
Lloyd Piqueba04e622017-12-14 17:11:26 -08001386 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001387}
1388
Steven Thomasb02664d2017-07-26 18:48:28 -07001389void SurfaceFlinger::onRefreshReceived(int sequenceId,
1390 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001391 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001392 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001393 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001394 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001395 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001396}
1397
Dan Stoza9e56aa02015-11-02 13:00:03 -08001398void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001399 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001400 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001401 getHwComposer().setVsyncEnabled(disp,
1402 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001403}
1404
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001405// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001406void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001407 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001408 // Clear the drawing state so that the logic inside of
1409 // handleTransactionLocked will fire. It will determine the delta between
1410 // mCurrentState and mDrawingState and re-apply all changes when we make the
1411 // transition.
1412 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001413 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001414 mDisplays.clear();
1415}
1416
Steven Thomas050b2c82017-03-06 11:45:16 -08001417void SurfaceFlinger::updateVrFlinger() {
1418 if (!mVrFlinger)
1419 return;
1420 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001421 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001422 return;
1423 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001424
David Sodman105b7dc2017-11-04 20:28:14 -07001425 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001426 ALOGE("Vr flinger is only supported for remote hardware composer"
1427 " service connections. Ignoring request to transition to vr"
1428 " flinger.");
1429 mVrFlingerRequestsDisplay = false;
1430 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001431 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001432
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001433 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001434
Steven Thomasb02664d2017-07-26 18:48:28 -07001435 int currentDisplayPowerMode = getDisplayDeviceLocked(
1436 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001437
Steven Thomasb02664d2017-07-26 18:48:28 -07001438 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001439 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001440 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001441
Steven Thomasb02664d2017-07-26 18:48:28 -07001442 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001443 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001444 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1445 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001446 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001447
David Sodman105b7dc2017-11-04 20:28:14 -07001448 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1449 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001450
1451 if (vrFlingerRequestsDisplay) {
1452 mVrFlinger->GrantDisplayOwnership();
1453 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001454 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001455 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001456
1457 mVisibleRegionsDirty = true;
1458 invalidateHwcGeometry();
1459
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001460 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001461 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1462 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1463 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001464
Steven Thomasb02664d2017-07-26 18:48:28 -07001465 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001466 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001467 const nsecs_t period = activeConfig->getVsyncPeriod();
1468 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001469
Steven Thomasb02664d2017-07-26 18:48:28 -07001470 // Use phase of 0 since phase is not known.
1471 // Use latency of 0, which will snap to the ideal latency.
1472 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001473
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001474 android_atomic_or(1, &mRepaintEverything);
1475 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001476}
1477
Mathias Agopian4fec8732012-06-29 14:12:52 -07001478void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001479 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001480 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001481 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001482 bool frameMissed = !mHadClientComposition &&
1483 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001484 (mPreviousPresentFence->getSignalTime() ==
1485 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001486 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001487 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001488 signalLayerUpdate();
1489 break;
1490 }
1491
Steven Thomas050b2c82017-03-06 11:45:16 -08001492 // Now that we're going to make it to the handleMessageTransaction()
1493 // call below it's safe to call updateVrFlinger(), which will
1494 // potentially trigger a display handoff.
1495 updateVrFlinger();
1496
Dan Stoza6b9454d2014-11-07 16:00:59 -08001497 bool refreshNeeded = handleMessageTransaction();
1498 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001499 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001500 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001501 // Signal a refresh if a transaction modified the window state,
1502 // a new buffer was latched, or if HWC has requested a full
1503 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001504 signalRefresh();
1505 }
1506 break;
1507 }
1508 case MessageQueue::REFRESH: {
1509 handleMessageRefresh();
1510 break;
1511 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001512 }
1513}
1514
Dan Stoza6b9454d2014-11-07 16:00:59 -08001515bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001516 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001517 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001518 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001519 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001520 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001521 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001522}
1523
Dan Stoza6b9454d2014-11-07 16:00:59 -08001524bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001525 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001526 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001527}
1528
1529void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001530 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001531
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001532 mRefreshPending = false;
1533
Chia-I Wu30505fb2018-03-26 16:20:31 -07001534 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001535
Chia-I Wu30505fb2018-03-26 16:20:31 -07001536 preComposition(refreshStartTime);
1537 rebuildLayerStacks();
1538 setUpHWComposer();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001539 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001540 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001541 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001542 doComposition();
Chia-I Wu30505fb2018-03-26 16:20:31 -07001543 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001544
David Sodman105b7dc2017-11-04 20:28:14 -07001545 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001546
1547 mHadClientComposition = false;
1548 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1549 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1550 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001551 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001552 }
Dan Stoza84d619e2018-03-28 17:07:36 -07001553 mVsyncModulator.setLastFrameUsedRenderEngine(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001554
Dan Stoza9e56aa02015-11-02 13:00:03 -08001555 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001556}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001557
Mathias Agopiancd60f992012-08-16 16:28:27 -07001558void SurfaceFlinger::doDebugFlashRegions()
1559{
1560 // is debugging enabled
1561 if (CC_LIKELY(!mDebugRegion))
1562 return;
1563
1564 const bool repaintEverything = mRepaintEverything;
1565 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1566 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001567 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001568 // transform the dirty region into this screen's coordinate space
1569 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1570 if (!dirtyRegion.isEmpty()) {
1571 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001572 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001573
1574 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001575 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001576 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001577 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1578
Mathias Agopianda27af92012-09-13 18:17:13 -07001579 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001580 }
1581 }
1582 }
1583
1584 postFramebuffer();
1585
1586 if (mDebugRegion > 1) {
1587 usleep(mDebugRegion * 1000);
1588 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001589
Dan Stoza9e56aa02015-11-02 13:00:03 -08001590 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001591 auto& displayDevice = mDisplays[displayId];
1592 if (!displayDevice->isDisplayOn()) {
1593 continue;
1594 }
1595
David Sodman105b7dc2017-11-04 20:28:14 -07001596 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1597 ALOGE_IF(result != NO_ERROR,
1598 "prepareFrame for display %zd failed:"
1599 " %d (%s)",
1600 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001601 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001602}
1603
Adrian Roos1e1a1282017-11-01 19:05:31 +01001604void SurfaceFlinger::doTracing(const char* where) {
1605 ATRACE_CALL();
1606 ATRACE_NAME(where);
1607 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001608 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001609 }
1610}
1611
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001612void SurfaceFlinger::logLayerStats() {
1613 ATRACE_CALL();
1614 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1615 int32_t hwcId = -1;
1616 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1617 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1618 if (displayDevice->isPrimary()) {
1619 hwcId = displayDevice->getHwcDisplayId();
1620 break;
1621 }
1622 }
1623 if (hwcId < 0) {
1624 ALOGE("LayerStats: Hmmm, no primary display?");
1625 return;
1626 }
1627 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1628 }
1629}
1630
Chia-I Wu30505fb2018-03-26 16:20:31 -07001631void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001632{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001633 ATRACE_CALL();
1634 ALOGV("preComposition");
1635
Mathias Agopiancd60f992012-08-16 16:28:27 -07001636 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001637 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001638 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001639 needExtraInvalidate = true;
1640 }
Robert Carr2047fae2016-11-28 14:09:09 -08001641 });
1642
Mathias Agopiancd60f992012-08-16 16:28:27 -07001643 if (needExtraInvalidate) {
1644 signalLayerUpdate();
1645 }
1646}
1647
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001648void SurfaceFlinger::updateCompositorTiming(
1649 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1650 std::shared_ptr<FenceTime>& presentFenceTime) {
1651 // Update queue of past composite+present times and determine the
1652 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001653 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001654 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001655 while (!getBE().mCompositePresentTimes.empty()) {
1656 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001657 // Cached values should have been updated before calling this method,
1658 // which helps avoid duplicate syscalls.
1659 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1660 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1661 break;
1662 }
1663 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001664 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001665 }
1666
1667 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001668 while (getBE().mCompositePresentTimes.size() > 16) {
1669 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001670 }
1671
Brian Andersond0010582017-03-07 13:20:31 -08001672 setCompositorTimingSnapped(
1673 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1674}
1675
1676void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1677 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001678 // Integer division and modulo round toward 0 not -inf, so we need to
1679 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001680 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001681 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1682 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1683
Brian Andersond0010582017-03-07 13:20:31 -08001684 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1685 if (idealLatency <= 0) {
1686 idealLatency = vsyncInterval;
1687 }
1688
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001689 // Snap the latency to a value that removes scheduling jitter from the
1690 // composition and present times, which often have >1ms of jitter.
1691 // Reducing jitter is important if an app attempts to extrapolate
1692 // something (such as user input) to an accurate diasplay time.
1693 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1694 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001695 nsecs_t bias = vsyncInterval / 2;
1696 int64_t extraVsyncs =
1697 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1698 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1699 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001700
David Sodman99974d22017-11-28 12:04:33 -08001701 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1702 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1703 getBE().mCompositorTiming.interval = vsyncInterval;
1704 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001705}
1706
Chia-I Wu30505fb2018-03-26 16:20:31 -07001707void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001708{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001709 ATRACE_CALL();
1710 ALOGV("postComposition");
1711
Brian Anderson3546a3f2016-07-14 11:51:14 -07001712 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001713 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001714 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001715 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001716 }
1717
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001718 // |mStateLock| not needed as we are on the main thread
1719 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001720
David Sodman73beded2017-11-15 11:56:06 -08001721 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001722 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001723 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001724 glCompositionDoneFenceTime =
1725 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001726 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001727 } else {
1728 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1729 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001730
David Sodman73beded2017-11-15 11:56:06 -08001731 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001732 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001733 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001734 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001735
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001736 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1737 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1738
Chia-I Wu30505fb2018-03-26 16:20:31 -07001739 // We use the refreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001740 // when we started doing work for this frame, but that should be okay
1741 // since updateCompositorTiming has snapping logic.
1742 updateCompositorTiming(
Chia-I Wu30505fb2018-03-26 16:20:31 -07001743 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001744 CompositorTiming compositorTiming;
1745 {
David Sodman99974d22017-11-28 12:04:33 -08001746 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1747 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001748 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001749
Robert Carr2047fae2016-11-28 14:09:09 -08001750 mDrawingState.traverseInZOrder([&](Layer* layer) {
1751 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001752 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001753 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001754 recordBufferingStats(layer->getName().string(),
1755 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001756 }
Robert Carr2047fae2016-11-28 14:09:09 -08001757 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001758
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001759 if (presentFenceTime->isValid()) {
1760 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001761 enableHardwareVsync();
1762 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001763 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001764 }
1765 }
1766
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001767 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001768 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001769 enableHardwareVsync();
1770 }
1771 }
1772
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001773 if (mAnimCompositionPending) {
1774 mAnimCompositionPending = false;
1775
Brian Anderson4e606e32017-03-16 15:34:57 -07001776 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001777 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001778 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001779 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001780 // The HWC doesn't support present fences, so use the refresh
1781 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001782 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001783 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001784 mAnimFrameTracker.setActualPresentTime(presentTime);
1785 }
1786 mAnimFrameTracker.advanceFrame();
1787 }
Dan Stozab90cf072015-03-05 11:05:59 -08001788
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001789 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1790 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001791 return;
1792 }
1793
1794 nsecs_t currentTime = systemTime();
1795 if (mHasPoweredOff) {
1796 mHasPoweredOff = false;
1797 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001798 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001799 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001800 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1801 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001802 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001803 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001804 }
David Sodman4a36e932017-11-07 14:29:47 -08001805 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001806 }
David Sodman4a36e932017-11-07 14:29:47 -08001807 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001808}
1809
1810void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001811 ATRACE_CALL();
1812 ALOGV("rebuildLayerStacks");
1813
Mathias Agopiancd60f992012-08-16 16:28:27 -07001814 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001815 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001816 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001817 mVisibleRegionsDirty = false;
1818 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001819
Jeff Sharkey76488112017-02-27 14:15:18 -07001820 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1821 Region opaqueRegion;
1822 Region dirtyRegion;
1823 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001824 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001825 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1826 const Transform& tr(displayDevice->getTransform());
1827 const Rect bounds(displayDevice->getBounds());
1828 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001829 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001830
Jeff Sharkey76488112017-02-27 14:15:18 -07001831 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001832 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001833 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1834 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001835 Region drawRegion(tr.transform(
1836 layer->visibleNonTransparentRegion));
1837 drawRegion.andSelf(bounds);
1838 if (!drawRegion.isEmpty()) {
1839 layersSortedByZ.add(layer);
1840 } else {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001841 // Clear out the HWC layer if this layer was
1842 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001843 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001844 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001845 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001846 } else {
1847 // WM changes displayDevice->layerStack upon sleep/awake.
1848 // Here we make sure we delete the HWC layers even if
1849 // WM changed their layer stack.
1850 hwcLayerDestroyed = layer->destroyHwcLayer(
1851 displayDevice->getHwcDisplayId());
Chia-I Wu83806892017-11-16 10:50:20 -08001852 }
1853
1854 // If a layer is not going to get a release fence because
1855 // it is invisible, but it is also going to release its
1856 // old buffer, add it to the list of layers needing
1857 // fences.
1858 if (hwcLayerDestroyed) {
1859 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1860 mLayersWithQueuedFrames.cend(), layer);
1861 if (found != mLayersWithQueuedFrames.cend()) {
1862 layersNeedingFences.add(layer);
1863 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001864 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001865 });
1866 }
1867 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001868 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001869 displayDevice->undefinedRegion.set(bounds);
1870 displayDevice->undefinedRegion.subtractSelf(
1871 tr.transform(opaqueRegion));
1872 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001873 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001874 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001875}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001876
Romain Guy0147a172017-06-01 13:53:56 -07001877mat4 SurfaceFlinger::computeSaturationMatrix() const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001878 if (mGlobalSaturationFactor == 1.0f) {
Romain Guy0147a172017-06-01 13:53:56 -07001879 return mat4();
1880 }
1881
1882 // Rec.709 luma coefficients
1883 float3 luminance{0.213f, 0.715f, 0.072f};
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001884 luminance *= 1.0f - mGlobalSaturationFactor;
Romain Guy0147a172017-06-01 13:53:56 -07001885 return mat4(
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001886 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
1887 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
1888 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
Romain Guy0147a172017-06-01 13:53:56 -07001889 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1890 );
1891}
1892
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001893// Returns a dataspace that fits all visible layers. The returned dataspace
1894// can only be one of
1895//
1896// - Dataspace::V0_SRGB
1897// - Dataspace::DISPLAY_P3
1898// - Dataspace::V0_SCRGB_LINEAR
1899// TODO(b/73825729) Add BT2020 data space.
1900ui::Dataspace SurfaceFlinger::getBestDataspace(
1901 const sp<const DisplayDevice>& displayDevice) const {
1902 Dataspace bestDataspace = Dataspace::V0_SRGB;
1903 for (const auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1904 switch (layer->getDataSpace()) {
1905 case Dataspace::V0_SCRGB:
1906 case Dataspace::V0_SCRGB_LINEAR:
1907 // return immediately
1908 return Dataspace::V0_SCRGB_LINEAR;
1909 case Dataspace::BT2020_PQ:
1910 case Dataspace::BT2020_ITU_PQ:
1911 // Historically, HDR dataspaces are ignored by SurfaceFlinger. But
1912 // since SurfaceFlinger simulates HDR support now, it should honor
1913 // them unless there is also native support.
Peiyong Lin62665892018-04-16 11:07:44 -07001914 if (!displayDevice->hasHDR10Support()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001915 return Dataspace::V0_SCRGB_LINEAR;
1916 }
1917 break;
1918 case Dataspace::DISPLAY_P3:
1919 bestDataspace = Dataspace::DISPLAY_P3;
1920 break;
1921 default:
1922 break;
1923 }
Romain Guy54f154a2017-10-24 21:40:32 +01001924 }
1925
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001926 return bestDataspace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001927}
1928
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001929// Pick the ColorMode / Dataspace for the display device.
1930// TODO(b/73825729) Add BT2020 color mode.
1931void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& displayDevice,
1932 ColorMode* outMode, Dataspace* outDataSpace) const {
1933 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1934 *outMode = ColorMode::NATIVE;
1935 *outDataSpace = Dataspace::UNKNOWN;
1936 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001937 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001938
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001939 switch (getBestDataspace(displayDevice)) {
1940 case Dataspace::DISPLAY_P3:
1941 case Dataspace::V0_SCRGB_LINEAR:
1942 *outMode = ColorMode::DISPLAY_P3;
1943 *outDataSpace = Dataspace::DISPLAY_P3;
1944 break;
1945 default:
1946 *outMode = ColorMode::SRGB;
1947 *outDataSpace = Dataspace::V0_SRGB;
1948 break;
1949 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001950}
1951
Chia-I Wu30505fb2018-03-26 16:20:31 -07001952void SurfaceFlinger::setUpHWComposer() {
1953 ATRACE_CALL();
1954 ALOGV("setUpHWComposer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08001955
Jesse Hall028dc8f2013-08-20 16:35:32 -07001956 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Dan Stozac7a25ad2018-04-12 11:45:09 -07001957 bool dirty = !mDisplays[dpy]->getDirtyRegion(mRepaintEverything).isEmpty();
Jesse Hallb7a05492014-08-14 15:45:06 -07001958 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1959 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1960
1961 // If nothing has changed (!dirty), don't recompose.
1962 // If something changed, but we don't currently have any visible layers,
1963 // and didn't when we last did a composition, then skip it this time.
1964 // The second rule does two things:
1965 // - When all layers are removed from a display, we'll emit one black
1966 // frame, then nothing more until we get new layers.
1967 // - When a display is created with a private layer stack, we won't
1968 // emit any black frames until a layer is added to the layer stack.
1969 bool mustRecompose = dirty && !(empty && wasEmpty);
1970
1971 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1972 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1973 mustRecompose ? "doing" : "skipping",
1974 dirty ? "+" : "-",
1975 empty ? "+" : "-",
1976 wasEmpty ? "+" : "-");
1977
Dan Stoza71433162014-02-04 16:22:36 -08001978 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001979
1980 if (mustRecompose) {
1981 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1982 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001983 }
1984
Chia-I Wu30505fb2018-03-26 16:20:31 -07001985 // build the h/w work list
1986 if (CC_UNLIKELY(mGeometryInvalid)) {
1987 mGeometryInvalid = false;
1988 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1989 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1990 const auto hwcId = displayDevice->getHwcDisplayId();
1991 if (hwcId >= 0) {
1992 const Vector<sp<Layer>>& currentLayers(
1993 displayDevice->getVisibleLayersSortedByZ());
1994 for (size_t i = 0; i < currentLayers.size(); i++) {
1995 const auto& layer = currentLayers[i];
1996 if (!layer->hasHwcLayer(hwcId)) {
1997 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
1998 layer->forceClientComposition(hwcId);
1999 continue;
2000 }
2001 }
2002
2003 layer->setGeometry(displayDevice, i);
2004 if (mDebugDisableHWC || mDebugRegion) {
2005 layer->forceClientComposition(hwcId);
2006 }
2007 }
2008 }
2009 }
2010 }
2011
2012
2013 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
2014
2015 // Set the per-frame data
2016 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2017 auto& displayDevice = mDisplays[displayId];
2018 const auto hwcId = displayDevice->getHwcDisplayId();
2019
2020 if (hwcId < 0) {
2021 continue;
2022 }
2023 if (colorMatrix != mPreviousColorMatrix) {
Yiwei Zhang60d1a192018-03-07 14:52:28 -08002024 displayDevice->setColorTransform(colorMatrix);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002025 status_t result = getBE().mHwc->setColorTransform(hwcId, colorMatrix);
2026 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
2027 "display %zd: %d", displayId, result);
2028 }
2029 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002030 if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2031 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Peiyong Lin62665892018-04-16 11:07:44 -07002032 !displayDevice->hasHDR10Support()) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07002033 layer->forceClientComposition(hwcId);
2034 }
2035
2036 if (layer->getForceClientComposition(hwcId)) {
2037 ALOGV("[%s] Requesting Client composition", layer->getName().string());
2038 layer->setCompositionType(hwcId, HWC2::Composition::Client);
2039 continue;
2040 }
2041
2042 layer->setPerFrameData(displayDevice);
2043 }
2044
2045 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002046 ColorMode colorMode;
2047 Dataspace dataSpace;
2048 pickColorMode(displayDevice, &colorMode, &dataSpace);
2049 setActiveColorModeInternal(displayDevice, colorMode, dataSpace);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002050 }
2051 }
2052
2053 mPreviousColorMatrix = colorMatrix;
2054
Dan Stoza9e56aa02015-11-02 13:00:03 -08002055 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002056 auto& displayDevice = mDisplays[displayId];
2057 if (!displayDevice->isDisplayOn()) {
2058 continue;
2059 }
2060
David Sodman105b7dc2017-11-04 20:28:14 -07002061 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002062 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2063 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002064 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002065}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002066
Mathias Agopiancd60f992012-08-16 16:28:27 -07002067void SurfaceFlinger::doComposition() {
2068 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002069 ALOGV("doComposition");
2070
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002071 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002072 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002073 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002074 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002075 // transform the dirty region into this screen's coordinate space
2076 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002077
2078 // repaint the framebuffer (if needed)
2079 doDisplayComposition(hw, dirtyRegion);
2080
Mathias Agopiancd60f992012-08-16 16:28:27 -07002081 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002082 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002083 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002084 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002085 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002086}
2087
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002088void SurfaceFlinger::postFramebuffer()
2089{
Mathias Agopian841cde52012-03-01 15:44:37 -08002090 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002091 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002092
Mathias Agopiana44b0412011-10-16 18:46:35 -07002093 const nsecs_t now = systemTime();
2094 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002095
Dan Stoza9e56aa02015-11-02 13:00:03 -08002096 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2097 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002098 if (!displayDevice->isDisplayOn()) {
2099 continue;
2100 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002101 const auto hwcId = displayDevice->getHwcDisplayId();
2102 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002103 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002104 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002105 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002106 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002107 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002108 // The layer buffer from the previous frame (if any) is released
2109 // by HWC only when the release fence from this frame (if any) is
2110 // signaled. Always get the release fence from HWC first.
2111 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002112 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002113
2114 // If the layer was client composited in the previous frame, we
2115 // need to merge with the previous client target acquire fence.
2116 // Since we do not track that, always merge with the current
2117 // client target acquire fence when it is available, even though
2118 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002119 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002120 releaseFence = Fence::merge("LayerRelease", releaseFence,
2121 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002122 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002123
David Sodmanb8af7922017-12-21 15:17:55 -08002124 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002125 }
Chia-I Wu83806892017-11-16 10:50:20 -08002126
2127 // We've got a list of layers needing fences, that are disjoint with
2128 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2129 // supply them with the present fence.
2130 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002131 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002132 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002133 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002134 }
2135 }
2136
Dan Stoza9e56aa02015-11-02 13:00:03 -08002137 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002138 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002139 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002140 }
2141
Mathias Agopiana44b0412011-10-16 18:46:35 -07002142 mLastSwapBufferTime = systemTime() - now;
2143 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002144
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002145 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002146 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2147 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2148 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2149 logFrameStats();
2150 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002151 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002152}
2153
Mathias Agopian87baae12012-07-31 12:38:26 -07002154void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002155{
Mathias Agopian841cde52012-03-01 15:44:37 -08002156 ATRACE_CALL();
2157
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002158 // here we keep a copy of the drawing state (that is the state that's
2159 // going to be overwritten by handleTransactionLocked()) outside of
2160 // mStateLock so that the side-effects of the State assignment
2161 // don't happen with mStateLock held (which can cause deadlocks).
2162 State drawingState(mDrawingState);
2163
Mathias Agopianca4d3602011-05-19 15:38:14 -07002164 Mutex::Autolock _l(mStateLock);
2165 const nsecs_t now = systemTime();
2166 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002167
Mathias Agopianca4d3602011-05-19 15:38:14 -07002168 // Here we're guaranteed that some transaction flags are set
2169 // so we can call handleTransactionLocked() unconditionally.
2170 // We call getTransactionFlags(), which will also clear the flags,
2171 // with mStateLock held to guarantee that mCurrentState won't change
2172 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002173
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002174 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002175 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002176 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002177
Mathias Agopianca4d3602011-05-19 15:38:14 -07002178 mLastTransactionTime = systemTime() - now;
2179 mDebugInTransaction = 0;
2180 invalidateHwcGeometry();
2181 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002182}
2183
Lloyd Pique715a2c12017-12-14 17:18:08 -08002184DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002185 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002186 // Figure out whether the event is for the primary display or an
2187 // external display by matching the Hwc display id against one for a
2188 // connected display. If we did not find a match, we then check what
2189 // displays are not already connected to determine the type. If we don't
2190 // have a connected primary display, we assume the new display is meant to
2191 // be the primary display, and then if we don't have an external display,
2192 // we assume it is that.
2193 const auto primaryDisplayId =
2194 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2195 const auto externalDisplayId =
2196 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2197 if (primaryDisplayId && primaryDisplayId == display) {
2198 return DisplayDevice::DISPLAY_PRIMARY;
2199 } else if (externalDisplayId && externalDisplayId == display) {
2200 return DisplayDevice::DISPLAY_EXTERNAL;
2201 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2202 return DisplayDevice::DISPLAY_PRIMARY;
2203 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2204 return DisplayDevice::DISPLAY_EXTERNAL;
2205 }
2206
2207 return DisplayDevice::DISPLAY_ID_INVALID;
2208}
2209
Lloyd Piqueba04e622017-12-14 17:11:26 -08002210void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2211 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002212 auto displayType = determineDisplayType(event.display, event.connection);
2213 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2214 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2215 continue;
2216 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002217
2218 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2219 ALOGE("External displays are not supported by the vr hardware composer.");
2220 continue;
2221 }
2222
Lloyd Pique715a2c12017-12-14 17:18:08 -08002223 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002224
2225 if (event.connection == HWC2::Connection::Connected) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002226 if (!mBuiltinDisplays[displayType].get()) {
2227 ALOGV("Creating built in display %d", displayType);
2228 mBuiltinDisplays[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002229 DisplayDeviceState info;
2230 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002231 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2232 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002233 info.isSecure = true; // All physical displays are currently considered secure.
Steven Thomaseb6d2052018-03-20 15:40:48 -07002234 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
2235 mInterceptor->saveDisplayCreation(info);
2236 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002237 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002238 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002239
Lloyd Piquefcd86612017-12-14 17:15:36 -08002240 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2241 if (idx >= 0) {
2242 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002243 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002244 mCurrentState.displays.removeItemsAt(idx);
2245 }
2246 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002247 }
2248
2249 processDisplayChangesLocked();
2250 }
2251
2252 mPendingHotplugEvents.clear();
2253}
2254
Lloyd Pique99d3da52018-01-22 17:48:03 -08002255sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2256 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2257 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002258 bool hasWideColorGamut = false;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002259 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002260 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002261 for (ColorMode colorMode : modes) {
2262 switch (colorMode) {
2263 case ColorMode::DISPLAY_P3:
2264 case ColorMode::ADOBE_RGB:
2265 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002266 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002267 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002268 // TODO(lpy) Handle BT2020, BT2100_PQ and BT2100_HLG properly.
Lloyd Pique99d3da52018-01-22 17:48:03 -08002269 default:
2270 break;
2271 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002272
2273 std::vector<RenderIntent> renderIntents = getHwComposer().getRenderIntents(hwcId,
2274 colorMode);
2275 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2276 for (auto intent : renderIntents) {
2277 if (intent == RenderIntent::ENHANCE) {
2278 mBuiltinDisplaySupportsEnhance = true;
2279 break;
2280 }
2281 }
2282 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002283 }
2284 }
2285
Peiyong Lin62665892018-04-16 11:07:44 -07002286 HdrCapabilities hdrCapabilities;
2287 getHwComposer().getHdrCapabilities(hwcId, &hdrCapabilities);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002288
2289 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2290 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2291
2292 /*
2293 * Create our display's surface
2294 */
2295 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2296 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
2297 renderSurface->setAsync(state.type >= DisplayDevice::DISPLAY_VIRTUAL);
2298 renderSurface->setNativeWindow(nativeWindow.get());
2299 const int displayWidth = renderSurface->queryWidth();
2300 const int displayHeight = renderSurface->queryHeight();
2301
2302 // Make sure that composition can never be stalled by a virtual display
2303 // consumer that isn't processing buffers fast enough. We have to do this
2304 // in two places:
2305 // * Here, in case the display is composed entirely by HWC.
2306 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2307 // window's swap interval in eglMakeCurrent, so they'll override the
2308 // interval we set here.
2309 if (state.type >= DisplayDevice::DISPLAY_VIRTUAL) {
2310 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2311 }
2312
2313 // virtual displays are always considered enabled
2314 auto initialPowerMode = (state.type >= DisplayDevice::DISPLAY_VIRTUAL) ? HWC_POWER_MODE_NORMAL
2315 : HWC_POWER_MODE_OFF;
2316
2317 sp<DisplayDevice> hw =
2318 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2319 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
Peiyong Lin0ac5f4e2018-04-19 22:06:34 -07002320 hasWideColorGamut, hdrCapabilities,
2321 getHwComposer().getSupportedPerFrameMetadata(hwcId),
2322 initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002323
2324 if (maxFrameBufferAcquiredBuffers >= 3) {
2325 nativeWindowSurface->preallocateBuffers();
2326 }
2327
2328 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002329 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2330 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002331 defaultColorMode = ColorMode::SRGB;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002332 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002333 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002334 setActiveColorModeInternal(hw, defaultColorMode, defaultDataSpace);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002335 hw->setLayerStack(state.layerStack);
2336 hw->setProjection(state.orientation, state.viewport, state.frame);
2337 hw->setDisplayName(state.displayName);
2338
2339 return hw;
2340}
2341
Lloyd Pique347200f2017-12-14 17:00:15 -08002342void SurfaceFlinger::processDisplayChangesLocked() {
2343 // here we take advantage of Vector's copy-on-write semantics to
2344 // improve performance by skipping the transaction entirely when
2345 // know that the lists are identical
2346 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2347 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2348 if (!curr.isIdenticalTo(draw)) {
2349 mVisibleRegionsDirty = true;
2350 const size_t cc = curr.size();
2351 size_t dc = draw.size();
2352
2353 // find the displays that were removed
2354 // (ie: in drawing state but not in current state)
2355 // also handle displays that changed
2356 // (ie: displays that are in both lists)
2357 for (size_t i = 0; i < dc;) {
2358 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2359 if (j < 0) {
2360 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002361 // Call makeCurrent() on the primary display so we can
2362 // be sure that nothing associated with this display
2363 // is current.
2364 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2365 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2366 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2367 if (hw != nullptr) hw->disconnect(getHwComposer());
2368 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2369 mEventThread->onHotplugReceived(draw[i].type, false);
2370 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002371 } else {
2372 // this display is in both lists. see if something changed.
2373 const DisplayDeviceState& state(curr[j]);
2374 const wp<IBinder>& display(curr.keyAt(j));
2375 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2376 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2377 if (state_binder != draw_binder) {
2378 // changing the surface is like destroying and
2379 // recreating the DisplayDevice, so we just remove it
2380 // from the drawing state, so that it get re-added
2381 // below.
2382 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2383 if (hw != nullptr) hw->disconnect(getHwComposer());
2384 mDisplays.removeItem(display);
2385 mDrawingState.displays.removeItemsAt(i);
2386 dc--;
2387 // at this point we must loop to the next item
2388 continue;
2389 }
2390
2391 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2392 if (disp != nullptr) {
2393 if (state.layerStack != draw[i].layerStack) {
2394 disp->setLayerStack(state.layerStack);
2395 }
2396 if ((state.orientation != draw[i].orientation) ||
2397 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2398 disp->setProjection(state.orientation, state.viewport, state.frame);
2399 }
2400 if (state.width != draw[i].width || state.height != draw[i].height) {
2401 disp->setDisplaySize(state.width, state.height);
2402 }
2403 }
2404 }
2405 ++i;
2406 }
2407
2408 // find displays that were added
2409 // (ie: in current state but not in drawing state)
2410 for (size_t i = 0; i < cc; i++) {
2411 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2412 const DisplayDeviceState& state(curr[i]);
2413
2414 sp<DisplaySurface> dispSurface;
2415 sp<IGraphicBufferProducer> producer;
2416 sp<IGraphicBufferProducer> bqProducer;
2417 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002418 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002419
2420 int32_t hwcId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002421 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002422 // Virtual displays without a surface are dormant:
2423 // they have external state (layer stack, projection,
2424 // etc.) but no internal state (i.e. a DisplayDevice).
2425 if (state.surface != nullptr) {
2426 // Allow VR composer to use virtual displays.
2427 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2428 int width = 0;
2429 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2430 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2431 int height = 0;
2432 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2433 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2434 int intFormat = 0;
2435 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2436 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002437 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002438
2439 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2440 }
2441
2442 // TODO: Plumb requested format back up to consumer
2443
2444 sp<VirtualDisplaySurface> vds =
2445 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2446 bqProducer, bqConsumer,
2447 state.displayName);
2448
2449 dispSurface = vds;
2450 producer = vds;
2451 }
2452 } else {
2453 ALOGE_IF(state.surface != nullptr,
2454 "adding a supported display, but rendering "
2455 "surface is provided (%p), ignoring it",
2456 state.surface.get());
2457
2458 hwcId = state.type;
2459 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2460 producer = bqProducer;
2461 }
2462
2463 const wp<IBinder>& display(curr.keyAt(i));
2464 if (dispSurface != nullptr) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002465 mDisplays.add(display,
2466 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2467 producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002468 if (!state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002469 mEventThread->onHotplugReceived(state.type, true);
2470 }
2471 }
2472 }
2473 }
2474 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002475
2476 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002477}
2478
Mathias Agopian87baae12012-07-31 12:38:26 -07002479void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002480{
Dan Stoza7dde5992015-05-22 09:51:44 -07002481 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002482 mCurrentState.traverseInZOrder([](Layer* layer) {
2483 layer->notifyAvailableFrames();
2484 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002485
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002486 /*
2487 * Traversal of the children
2488 * (perform the transaction for each of them if needed)
2489 */
2490
Mathias Agopian3559b072012-08-15 13:46:03 -07002491 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002492 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002493 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002494 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002495
2496 const uint32_t flags = layer->doTransaction(0);
2497 if (flags & Layer::eVisibleRegion)
2498 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002499 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002500 }
2501
2502 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002503 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002504 */
2505
Mathias Agopiane57f2922012-08-09 16:29:12 -07002506 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002507 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002508 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002509 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002510
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002511 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002512 // The transform hint might have changed for some layers
2513 // (either because a display has changed, or because a layer
2514 // as changed).
2515 //
2516 // Walk through all the layers in currentLayers,
2517 // and update their transform hint.
2518 //
2519 // If a layer is visible only on a single display, then that
2520 // display is used to calculate the hint, otherwise we use the
2521 // default display.
2522 //
2523 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2524 // the hint is set before we acquire a buffer from the surface texture.
2525 //
2526 // NOTE: layer transactions have taken place already, so we use their
2527 // drawing state. However, SurfaceFlinger's own transaction has not
2528 // happened yet, so we must use the current state layer list
2529 // (soon to become the drawing state list).
2530 //
2531 sp<const DisplayDevice> disp;
2532 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002533 bool first = true;
2534 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002535 // NOTE: we rely on the fact that layers are sorted by
2536 // layerStack first (so we don't have to traverse the list
2537 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002538 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002539 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002540 currentlayerStack = layerStack;
2541 // figure out if this layerstack is mirrored
2542 // (more than one display) if so, pick the default display,
2543 // if not, pick the only display it's on.
2544 disp.clear();
2545 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2546 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002547 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002548 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002549 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002550 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002551 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002552 break;
2553 }
2554 }
2555 }
2556 }
Chet Haase91d25932013-04-11 15:24:55 -07002557
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002558 if (disp == nullptr) {
2559 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2560 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002561
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002562 // could be null when this layer is using a layerStack
2563 // that is not visible on any display. Also can occur at
2564 // screen off/on times.
2565 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002566 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002567
2568 // disp can be null if there is no display available at all to get
2569 // the transform hint from.
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002570 if (disp != nullptr) {
2571 layer->updateTransformHint(disp);
2572 }
Robert Carr2047fae2016-11-28 14:09:09 -08002573
2574 first = false;
2575 });
Mathias Agopian84300952012-11-21 16:02:13 -08002576 }
2577
2578
Mathias Agopian3559b072012-08-15 13:46:03 -07002579 /*
2580 * Perform our own transaction if needed
2581 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002582
2583 if (mLayersAdded) {
2584 mLayersAdded = false;
2585 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002586 mVisibleRegionsDirty = true;
2587 }
2588
2589 // some layers might have been removed, so
2590 // we need to update the regions they're exposing.
2591 if (mLayersRemoved) {
2592 mLayersRemoved = false;
2593 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002594 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002595 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002596 // this layer is not visible anymore
2597 // TODO: we could traverse the tree from front to back and
2598 // compute the actual visible region
2599 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002600 Region visibleReg;
2601 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002602 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002603 }
Robert Carr2047fae2016-11-28 14:09:09 -08002604 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002605 }
2606
2607 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002608
2609 updateCursorAsync();
2610}
2611
2612void SurfaceFlinger::updateCursorAsync()
2613{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002614 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2615 auto& displayDevice = mDisplays[displayId];
2616 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002617 continue;
2618 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002619
2620 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2621 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002622 }
2623 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002624}
2625
2626void SurfaceFlinger::commitTransaction()
2627{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002628 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002629 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002630 for (const auto& l : mLayersPendingRemoval) {
2631 recordBufferingStats(l->getName().string(),
2632 l->getOccupancyHistory(true));
2633 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002634 }
2635 mLayersPendingRemoval.clear();
2636 }
2637
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002638 // If this transaction is part of a window animation then the next frame
2639 // we composite should be considered an animation as well.
2640 mAnimCompositionPending = mAnimTransactionPending;
2641
Mathias Agopian4fec8732012-06-29 14:12:52 -07002642 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002643 mDrawingState.traverseInZOrder([](Layer* layer) {
2644 layer->commitChildList();
2645 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002646 mTransactionPending = false;
2647 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002648 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002649}
2650
Chia-I Wuab0c3192017-08-01 11:29:00 -07002651void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002652 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002653{
Mathias Agopian841cde52012-03-01 15:44:37 -08002654 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002655 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002656
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002657 Region aboveOpaqueLayers;
2658 Region aboveCoveredLayers;
2659 Region dirty;
2660
Mathias Agopian87baae12012-07-31 12:38:26 -07002661 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002662
Robert Carr2047fae2016-11-28 14:09:09 -08002663 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002664 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002665 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002666
Jesse Hall01e29052013-02-19 16:13:35 -08002667 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002668 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002669 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002670
Mathias Agopianab028732010-03-16 16:41:46 -07002671 /*
2672 * opaqueRegion: area of a surface that is fully opaque.
2673 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002674 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002675
2676 /*
2677 * visibleRegion: area of a surface that is visible on screen
2678 * and not fully transparent. This is essentially the layer's
2679 * footprint minus the opaque regions above it.
2680 * Areas covered by a translucent surface are considered visible.
2681 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002682 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002683
2684 /*
2685 * coveredRegion: area of a surface that is covered by all
2686 * visible regions above it (which includes the translucent areas).
2687 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002688 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002689
Jesse Halla8026d22012-09-25 13:25:04 -07002690 /*
2691 * transparentRegion: area of a surface that is hinted to be completely
2692 * transparent. This is only used to tell when the layer has no visible
2693 * non-transparent regions and can be removed from the layer list. It
2694 * does not affect the visibleRegion of this layer or any layers
2695 * beneath it. The hint may not be correct if apps don't respect the
2696 * SurfaceView restrictions (which, sadly, some don't).
2697 */
2698 Region transparentRegion;
2699
Mathias Agopianab028732010-03-16 16:41:46 -07002700
2701 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002702 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002703 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002704 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002705 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002706 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002707 if (!visibleRegion.isEmpty()) {
2708 // Remove the transparent area from the visible region
2709 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002710 if (tr.preserveRects()) {
2711 // transform the transparent region
2712 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002713 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002714 // transformation too complex, can't do the
2715 // transparent region optimization.
2716 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002717 }
Mathias Agopianab028732010-03-16 16:41:46 -07002718 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002719
Mathias Agopianab028732010-03-16 16:41:46 -07002720 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002721 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002722 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002723 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2724 // the opaque region is the layer's footprint
2725 opaqueRegion = visibleRegion;
2726 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002727 }
2728 }
2729
Robert Carre5f4f692018-01-12 13:12:28 -08002730 if (visibleRegion.isEmpty()) {
2731 layer->clearVisibilityRegions();
2732 return;
2733 }
2734
Mathias Agopianab028732010-03-16 16:41:46 -07002735 // Clip the covered region to the visible region
2736 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2737
2738 // Update aboveCoveredLayers for next (lower) layer
2739 aboveCoveredLayers.orSelf(visibleRegion);
2740
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002741 // subtract the opaque region covered by the layers above us
2742 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002743
2744 // compute this layer's dirty region
2745 if (layer->contentDirty) {
2746 // we need to invalidate the whole region
2747 dirty = visibleRegion;
2748 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002749 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002750 layer->contentDirty = false;
2751 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002752 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002753 * the exposed region consists of two components:
2754 * 1) what's VISIBLE now and was COVERED before
2755 * 2) what's EXPOSED now less what was EXPOSED before
2756 *
2757 * note that (1) is conservative, we start with the whole
2758 * visible region but only keep what used to be covered by
2759 * something -- which mean it may have been exposed.
2760 *
2761 * (2) handles areas that were not covered by anything but got
2762 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002763 */
Mathias Agopianab028732010-03-16 16:41:46 -07002764 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002765 const Region oldVisibleRegion = layer->visibleRegion;
2766 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002767 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2768 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002769 }
2770 dirty.subtractSelf(aboveOpaqueLayers);
2771
2772 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002773 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002774
Mathias Agopianab028732010-03-16 16:41:46 -07002775 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002776 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002777
Jesse Halla8026d22012-09-25 13:25:04 -07002778 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002779 layer->setVisibleRegion(visibleRegion);
2780 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002781 layer->setVisibleNonTransparentRegion(
2782 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002783 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002784
Mathias Agopian87baae12012-07-31 12:38:26 -07002785 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002786}
2787
Chia-I Wuab0c3192017-08-01 11:29:00 -07002788void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002789 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002790 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002791 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002792 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002793 }
2794 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002795}
2796
Dan Stoza6b9454d2014-11-07 16:00:59 -08002797bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002798{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002799 ALOGV("handlePageFlip");
2800
Brian Andersond6927fb2016-07-23 23:37:30 -07002801 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002802
Mathias Agopian4fec8732012-06-29 14:12:52 -07002803 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002804 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002805 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002806
2807 // Store the set of layers that need updates. This set must not change as
2808 // buffers are being latched, as this could result in a deadlock.
2809 // Example: Two producers share the same command stream and:
2810 // 1.) Layer 0 is latched
2811 // 2.) Layer 0 gets a new frame
2812 // 2.) Layer 1 gets a new frame
2813 // 3.) Layer 1 is latched.
2814 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2815 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002816 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002817 if (layer->hasQueuedFrame()) {
2818 frameQueued = true;
2819 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002820 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002821 } else {
2822 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002823 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002824 } else {
2825 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002826 }
Robert Carr2047fae2016-11-28 14:09:09 -08002827 });
2828
Dan Stoza9e56aa02015-11-02 13:00:03 -08002829 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002830 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002831 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002832 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002833 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002834 newDataLatched = true;
2835 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002836 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002837
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002838 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002839
2840 // If we will need to wake up at some time in the future to deal with a
2841 // queued frame that shouldn't be displayed during this vsync period, wake
2842 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002843 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002844 signalLayerUpdate();
2845 }
2846
2847 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002848 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002849}
2850
Mathias Agopianad456f92011-01-13 17:53:01 -08002851void SurfaceFlinger::invalidateHwcGeometry()
2852{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002853 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002854}
2855
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002856
Fabien Sanglard830b8472016-11-30 16:35:58 -08002857void SurfaceFlinger::doDisplayComposition(
2858 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002859 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002860{
Dan Stoza71433162014-02-04 16:22:36 -08002861 // We only need to actually compose the display if:
2862 // 1) It is being handled by hardware composer, which may need this to
2863 // keep its virtual display state machine in sync, or
2864 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002865 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002866 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002867 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002868 return;
2869 }
2870
Dan Stoza9e56aa02015-11-02 13:00:03 -08002871 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002872 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002873
2874 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002875 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002876}
2877
Chia-I Wub02087d2017-11-09 10:19:54 -08002878bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002879{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002880 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002881
Chia-I Wub02087d2017-11-09 10:19:54 -08002882 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002883 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002884 const auto hwcId = displayDevice->getHwcDisplayId();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002885 const bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
2886 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
2887 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2888 HWC2::Capability::SkipClientColorTransform);
2889 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002890
2891 mat4 oldColorMatrix;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002892 mat4 legacySrgbSaturationMatrix = mLegacySrgbSaturationMatrix;
2893 const bool applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002894 if (applyColorMatrix) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002895 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002896 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002897 legacySrgbSaturationMatrix = colorMatrix * legacySrgbSaturationMatrix;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002898 }
2899
Dan Stoza9e56aa02015-11-02 13:00:03 -08002900 if (hasClientComposition) {
2901 ALOGV("hasClientComposition");
2902
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002903 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002904 if (displayDevice->hasWideColorGamut()) {
2905 outputDataspace = displayDevice->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002906 }
2907 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
2908
Chia-I Wu7f402902017-11-09 12:51:10 -08002909 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002910 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskibf170d92018-04-19 15:08:05 -07002911 displayDevice->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08002912 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002913
2914 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002915 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002916 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2917 }
2918 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002919 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002920
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002921 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002922 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002923 // when using overlays, we assume a fully transparent framebuffer
2924 // NOTE: we could reduce how much we need to clear, for instance
2925 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002926 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002927 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002928 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002929 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002930 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002931 // we're left with the letterbox region
2932 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002933 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002934
2935 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002936 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002937
Mathias Agopianb9494d52012-04-18 02:28:45 -07002938 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002939 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002940 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002941 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002942 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002943 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002944
Dan Stoza9e56aa02015-11-02 13:00:03 -08002945 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002946 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002947 // scissor on the main display. It should never be needed
2948 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002949 const Rect& bounds(displayDevice->getBounds());
2950 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002951 if (scissor != bounds) {
2952 // scissor doesn't match the screen's dimensions, so we
2953 // need to clear everything outside of it and enable
2954 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002955
Mathias Agopianf45c5102012-10-24 16:29:17 -07002956 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002957 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002958 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002959 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002960 }
2961 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002962 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002963
Mathias Agopian85d751c2012-08-29 16:59:24 -07002964 /*
2965 * and then, render the layers targeted at the framebuffer
2966 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002967
Dan Stoza9e56aa02015-11-02 13:00:03 -08002968 ALOGV("Rendering client layers");
2969 const Transform& displayTransform = displayDevice->getTransform();
2970 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002971 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002972 bool firstLayer = true;
2973 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002974 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002975 displayTransform.transform(layer->visibleRegion)));
2976 ALOGV("Layer: %s", layer->getName().string());
2977 ALOGV(" Composition type: %s",
2978 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002979 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002980 switch (layer->getCompositionType(hwcId)) {
2981 case HWC2::Composition::Cursor:
2982 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002983 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002984 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002985 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002986 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002987 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002988 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002989 // never clear the very first layer since we're
2990 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002991 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002992 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002993 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002994 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002995 case HWC2::Composition::Client: {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002996 // Only apply saturation matrix layer that is legacy SRGB dataspace
2997 // when auto color mode is on.
2998 bool restore = false;
2999 mat4 savedMatrix;
3000 if (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
3001 layer->isLegacySrgbDataSpace()) {
3002 savedMatrix =
3003 getRenderEngine().setupColorTransform(legacySrgbSaturationMatrix);
3004 restore = true;
3005 }
chaviwa76b2712017-09-20 12:02:26 -07003006 layer->draw(renderArea, clip);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003007 if (restore) {
3008 getRenderEngine().setupColorTransform(savedMatrix);
3009 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003010 break;
3011 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003012 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07003013 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003014 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003015 } else {
3016 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003017 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003018 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003019 }
3020 } else {
3021 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08003022 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08003023 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08003024 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07003025 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07003026 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07003027 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003028 }
3029 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003030
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003031 if (applyColorMatrix) {
3032 getRenderEngine().setupColorTransform(oldColorMatrix);
3033 }
3034
Mathias Agopianf45c5102012-10-24 16:29:17 -07003035 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003036 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003037 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003038}
3039
Fabien Sanglard830b8472016-11-30 16:35:58 -08003040void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
3041 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003042 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003043 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003044}
3045
Dan Stoza7d89d062015-04-30 13:29:25 -07003046status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003047 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003048 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003049 const sp<Layer>& lbc,
3050 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003051{
Dan Stoza7d89d062015-04-30 13:29:25 -07003052 // add this layer to the current state list
3053 {
3054 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003055 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003056 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3057 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003058 return NO_MEMORY;
3059 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003060 if (parent == nullptr) {
3061 mCurrentState.layersSortedByZ.add(lbc);
3062 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003063 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003064 ALOGE("addClientLayer called with a removed parent");
3065 return NAME_NOT_FOUND;
3066 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003067 parent->addChild(lbc);
3068 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003069
Dan Stoza101d8dc2018-02-27 15:42:25 -08003070 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
Dan Stoza0a0158c2018-03-16 13:38:54 -07003071 // TODO (b/74616334): Change this back to a fatal assert once the leak is fixed
3072 ALOGE_IF(mGraphicBufferProducerList.size() > mMaxGraphicBufferProducerListSize,
3073 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3074 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize,
3075 mNumLayers);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003076 mLayersAdded = true;
3077 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003078 }
3079
Mathias Agopian96f08192010-06-02 23:28:45 -07003080 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003081 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003082
Dan Stoza7d89d062015-04-30 13:29:25 -07003083 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003084}
3085
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003086status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003087 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003088 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3089}
Robert Carr7f9b8992017-03-10 11:08:39 -08003090
chaviwca27f252018-02-06 16:46:39 -08003091status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3092 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003093 if (layer->isPendingRemoval()) {
3094 return NO_ERROR;
3095 }
3096
Robert Carr1f0a16a2016-10-24 16:27:39 -07003097 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003098 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003099 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003100 if (topLevelOnly) {
3101 return NO_ERROR;
3102 }
3103
Chia-I Wu98f1c102017-05-30 14:54:08 -07003104 sp<Layer> ancestor = p;
3105 while (ancestor->getParent() != nullptr) {
3106 ancestor = ancestor->getParent();
3107 }
3108 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3109 ALOGE("removeLayer called with a layer whose parent has been removed");
3110 return NAME_NOT_FOUND;
3111 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003112
3113 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003114 } else {
3115 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003116 }
3117
Robert Carr136e2f62017-02-08 17:54:29 -08003118 // As a matter of normal operation, the LayerCleaner will produce a second
3119 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3120 // so we will succeed in promoting it, but it's already been removed
3121 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3122 // otherwise something has gone wrong and we are leaking the layer.
3123 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003124 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3125 layer->getName().string(),
3126 (p != nullptr) ? p->getName().string() : "no-parent");
3127 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003128 } else if (index < 0) {
3129 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003130 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003131
Chia-I Wuc6657022017-08-15 11:18:17 -07003132 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003133 mLayersPendingRemoval.add(layer);
3134 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003135 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003136 setTransactionFlags(eTransactionNeeded);
3137 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003138}
3139
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003140uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003141 return android_atomic_release_load(&mTransactionFlags);
3142}
3143
Mathias Agopian3f844832013-08-07 21:24:32 -07003144uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003145 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3146}
3147
Mathias Agopian3f844832013-08-07 21:24:32 -07003148uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003149 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3150}
3151
3152uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3153 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003154 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003155 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003156 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003157 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003158 }
3159 return old;
3160}
3161
chaviwca27f252018-02-06 16:46:39 -08003162bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3163 for (const ComposerState& state : states) {
3164 // Here we need to check that the interface we're given is indeed
3165 // one of our own. A malicious client could give us a nullptr
3166 // IInterface, or one of its own or even one of our own but a
3167 // different type. All these situations would cause us to crash.
3168 if (state.client == nullptr) {
3169 return true;
3170 }
3171
3172 sp<IBinder> binder = IInterface::asBinder(state.client);
3173 if (binder == nullptr) {
3174 return true;
3175 }
3176
3177 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3178 return true;
3179 }
3180 }
3181 return false;
3182}
3183
Mathias Agopian8b33f032012-07-24 20:43:54 -07003184void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003185 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003186 const Vector<DisplayState>& displays,
3187 uint32_t flags)
3188{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003189 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003190 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003191 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003192
chaviwca27f252018-02-06 16:46:39 -08003193 if (containsAnyInvalidClientState(states)) {
3194 return;
3195 }
3196
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003197 if (flags & eAnimation) {
3198 // For window updates that are part of an animation we must wait for
3199 // previous animation "frames" to be handled.
3200 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003201 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003202 if (CC_UNLIKELY(err != NO_ERROR)) {
3203 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003204 // caller after a few seconds.
3205 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3206 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003207 mAnimTransactionPending = false;
3208 break;
3209 }
3210 }
3211 }
3212
chaviwca27f252018-02-06 16:46:39 -08003213 for (const DisplayState& display : displays) {
3214 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003215 }
3216
chaviwca27f252018-02-06 16:46:39 -08003217 for (const ComposerState& state : states) {
3218 transactionFlags |= setClientStateLocked(state);
3219 }
3220
3221 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3222 // as destroyed should only occur after setting all other states. This is to allow for a
3223 // child re-parent to happen before marking its original parent as destroyed (which would
3224 // then mark the child as destroyed).
3225 for (const ComposerState& state : states) {
3226 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003227 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003228
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003229 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3230 // anyway. This can be used as a flush mechanism for previous async transactions.
3231 // Empty animation transaction can be used to simulate back-pressure, so also force a
3232 // transaction for empty animation transactions.
3233 if (transactionFlags == 0 &&
3234 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003235 transactionFlags = eTransactionNeeded;
3236 }
3237
Mathias Agopian386aa982011-11-07 21:58:03 -08003238 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003239 if (mInterceptor->isEnabled()) {
3240 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003241 }
Irvel468051e2016-06-13 16:44:44 -07003242
Mathias Agopian386aa982011-11-07 21:58:03 -08003243 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003244 const auto start = (flags & eEarlyWakeup)
3245 ? VSyncModulator::TransactionStart::EARLY
3246 : VSyncModulator::TransactionStart::NORMAL;
3247 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003248
3249 // if this is a synchronous transaction, wait for it to take effect
3250 // before returning.
3251 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003252 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003253 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003254 if (flags & eAnimation) {
3255 mAnimTransactionPending = true;
3256 }
3257 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003258 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3259 if (CC_UNLIKELY(err != NO_ERROR)) {
3260 // just in case something goes wrong in SF, return to the
3261 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003262 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3263 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003264 break;
3265 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003266 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003267 }
3268}
3269
Mathias Agopiane57f2922012-08-09 16:29:12 -07003270uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3271{
Jesse Hall9a143922012-10-04 16:29:19 -07003272 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3273 if (dpyIdx < 0)
3274 return 0;
3275
Mathias Agopiane57f2922012-08-09 16:29:12 -07003276 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003277 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003278 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003279 const uint32_t what = s.what;
3280 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003281 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003282 disp.surface = s.surface;
3283 flags |= eDisplayTransactionNeeded;
3284 }
3285 }
3286 if (what & DisplayState::eLayerStackChanged) {
3287 if (disp.layerStack != s.layerStack) {
3288 disp.layerStack = s.layerStack;
3289 flags |= eDisplayTransactionNeeded;
3290 }
3291 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003292 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003293 if (disp.orientation != s.orientation) {
3294 disp.orientation = s.orientation;
3295 flags |= eDisplayTransactionNeeded;
3296 }
3297 if (disp.frame != s.frame) {
3298 disp.frame = s.frame;
3299 flags |= eDisplayTransactionNeeded;
3300 }
3301 if (disp.viewport != s.viewport) {
3302 disp.viewport = s.viewport;
3303 flags |= eDisplayTransactionNeeded;
3304 }
3305 }
Michael Lentine47e45402014-07-18 15:34:25 -07003306 if (what & DisplayState::eDisplaySizeChanged) {
3307 if (disp.width != s.width) {
3308 disp.width = s.width;
3309 flags |= eDisplayTransactionNeeded;
3310 }
3311 if (disp.height != s.height) {
3312 disp.height = s.height;
3313 flags |= eDisplayTransactionNeeded;
3314 }
3315 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003316 }
3317 return flags;
3318}
3319
chaviwca27f252018-02-06 16:46:39 -08003320uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3321 const layer_state_t& s = composerState.state;
3322 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3323
Mathias Agopian13127d82013-03-05 17:47:11 -08003324 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003325 if (layer == nullptr) {
3326 return 0;
3327 }
3328
3329 if (layer->isPendingRemoval()) {
3330 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3331 return 0;
3332 }
3333
3334 uint32_t flags = 0;
3335
3336 const uint32_t what = s.what;
3337 bool geometryAppliesWithResize =
3338 what & layer_state_t::eGeometryAppliesWithResize;
3339 if (what & layer_state_t::ePositionChanged) {
3340 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3341 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003342 }
chaviw8b3871a2017-11-01 17:41:01 -07003343 }
3344 if (what & layer_state_t::eLayerChanged) {
3345 // NOTE: index needs to be calculated before we update the state
3346 const auto& p = layer->getParent();
3347 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003348 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003349 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003350 mCurrentState.layersSortedByZ.removeAt(idx);
3351 mCurrentState.layersSortedByZ.add(layer);
3352 // we need traversal (state changed)
3353 // AND transaction (list changed)
3354 flags |= eTransactionNeeded|eTraversalNeeded;
3355 }
chaviw8b3871a2017-11-01 17:41:01 -07003356 } else {
3357 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003358 flags |= eTransactionNeeded|eTraversalNeeded;
3359 }
3360 }
chaviw8b3871a2017-11-01 17:41:01 -07003361 }
3362 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003363 // NOTE: index needs to be calculated before we update the state
3364 const auto& p = layer->getParent();
3365 if (p == nullptr) {
3366 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3367 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3368 mCurrentState.layersSortedByZ.removeAt(idx);
3369 mCurrentState.layersSortedByZ.add(layer);
3370 // we need traversal (state changed)
3371 // AND transaction (list changed)
3372 flags |= eTransactionNeeded|eTraversalNeeded;
3373 }
3374 } else {
3375 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3376 flags |= eTransactionNeeded|eTraversalNeeded;
3377 }
chaviw8b3871a2017-11-01 17:41:01 -07003378 }
3379 }
3380 if (what & layer_state_t::eSizeChanged) {
3381 if (layer->setSize(s.w, s.h)) {
3382 flags |= eTraversalNeeded;
3383 }
3384 }
3385 if (what & layer_state_t::eAlphaChanged) {
3386 if (layer->setAlpha(s.alpha))
3387 flags |= eTraversalNeeded;
3388 }
3389 if (what & layer_state_t::eColorChanged) {
3390 if (layer->setColor(s.color))
3391 flags |= eTraversalNeeded;
3392 }
3393 if (what & layer_state_t::eMatrixChanged) {
3394 if (layer->setMatrix(s.matrix))
3395 flags |= eTraversalNeeded;
3396 }
3397 if (what & layer_state_t::eTransparentRegionChanged) {
3398 if (layer->setTransparentRegionHint(s.transparentRegion))
3399 flags |= eTraversalNeeded;
3400 }
3401 if (what & layer_state_t::eFlagsChanged) {
3402 if (layer->setFlags(s.flags, s.mask))
3403 flags |= eTraversalNeeded;
3404 }
3405 if (what & layer_state_t::eCropChanged) {
3406 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3407 flags |= eTraversalNeeded;
3408 }
3409 if (what & layer_state_t::eFinalCropChanged) {
3410 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3411 flags |= eTraversalNeeded;
3412 }
3413 if (what & layer_state_t::eLayerStackChanged) {
3414 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3415 // We only allow setting layer stacks for top level layers,
3416 // everything else inherits layer stack from its parent.
3417 if (layer->hasParent()) {
3418 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3419 layer->getName().string());
3420 } else if (idx < 0) {
3421 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3422 "that also does not appear in the top level layer list. Something"
3423 " has gone wrong.", layer->getName().string());
3424 } else if (layer->setLayerStack(s.layerStack)) {
3425 mCurrentState.layersSortedByZ.removeAt(idx);
3426 mCurrentState.layersSortedByZ.add(layer);
3427 // we need traversal (state changed)
3428 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003429 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003430 }
3431 }
3432 if (what & layer_state_t::eDeferTransaction) {
3433 if (s.barrierHandle != nullptr) {
3434 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3435 } else if (s.barrierGbp != nullptr) {
3436 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3437 if (authenticateSurfaceTextureLocked(gbp)) {
3438 const auto& otherLayer =
3439 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3440 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3441 } else {
3442 ALOGE("Attempt to defer transaction to to an"
3443 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003444 }
3445 }
chaviw8b3871a2017-11-01 17:41:01 -07003446 // We don't trigger a traversal here because if no other state is
3447 // changed, we don't want this to cause any more work
3448 }
3449 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003450 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003451 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003452 if (!hadParent) {
3453 mCurrentState.layersSortedByZ.remove(layer);
3454 }
chaviw8b3871a2017-11-01 17:41:01 -07003455 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003456 }
chaviw8b3871a2017-11-01 17:41:01 -07003457 }
3458 if (what & layer_state_t::eReparentChildren) {
3459 if (layer->reparentChildren(s.reparentHandle)) {
3460 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003461 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003462 }
chaviw8b3871a2017-11-01 17:41:01 -07003463 if (what & layer_state_t::eDetachChildren) {
3464 layer->detachChildren();
3465 }
3466 if (what & layer_state_t::eOverrideScalingModeChanged) {
3467 layer->setOverrideScalingMode(s.overrideScalingMode);
3468 // We don't trigger a traversal here because if no other state is
3469 // changed, we don't want this to cause any more work
3470 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003471 return flags;
3472}
3473
chaviwca27f252018-02-06 16:46:39 -08003474void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3475 const layer_state_t& state = composerState.state;
3476 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3477
3478 sp<Layer> layer(client->getLayerUser(state.surface));
3479 if (layer == nullptr) {
3480 return;
3481 }
3482
3483 if (layer->isPendingRemoval()) {
3484 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3485 return;
3486 }
3487
3488 if (state.what & layer_state_t::eDestroySurface) {
3489 removeLayerLocked(mStateLock, layer);
3490 }
3491}
3492
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003493status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003494 const String8& name,
3495 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003496 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003497 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003498 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003499{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003500 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003501 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003502 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003503 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003504 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003505
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003506 status_t result = NO_ERROR;
3507
3508 sp<Layer> layer;
3509
Cody Northropbc755282017-03-31 12:00:08 -06003510 String8 uniqueName = getUniqueLayerName(name);
3511
Mathias Agopian3165cc22012-08-08 19:42:09 -07003512 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3513 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003514 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003515 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003516 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003517
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003518 break;
chaviw13fdc492017-06-27 12:40:18 -07003519 case ISurfaceComposerClient::eFXSurfaceColor:
3520 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003521 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003522 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003523 break;
3524 default:
3525 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003526 break;
3527 }
3528
Dan Stoza7d89d062015-04-30 13:29:25 -07003529 if (result != NO_ERROR) {
3530 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003531 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003532
Chia-I Wuab0c3192017-08-01 11:29:00 -07003533 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3534 // TODO b/64227542
3535 if (windowType == 441731) {
3536 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3537 layer->setPrimaryDisplayOnly();
3538 }
3539
Albert Chaulk479c60c2017-01-27 14:21:34 -05003540 layer->setInfo(windowType, ownerUid);
3541
Robert Carr1f0a16a2016-10-24 16:27:39 -07003542 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003543 if (result != NO_ERROR) {
3544 return result;
3545 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003546 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003547
3548 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003549 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003550}
3551
Cody Northropbc755282017-03-31 12:00:08 -06003552String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3553{
3554 bool matchFound = true;
3555 uint32_t dupeCounter = 0;
3556
3557 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3558 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3559
3560 // Loop over layers until we're sure there is no matching name
3561 while (matchFound) {
3562 matchFound = false;
3563 mDrawingState.traverseInZOrder([&](Layer* layer) {
3564 if (layer->getName() == uniqueName) {
3565 matchFound = true;
3566 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3567 }
3568 });
3569 }
3570
3571 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3572
3573 return uniqueName;
3574}
3575
David Sodman0c69cad2017-08-21 12:12:51 -07003576status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003577 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3578 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003579{
3580 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003581 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003582 case PIXEL_FORMAT_TRANSPARENT:
3583 case PIXEL_FORMAT_TRANSLUCENT:
3584 format = PIXEL_FORMAT_RGBA_8888;
3585 break;
3586 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003587 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003588 break;
3589 }
3590
David Sodman0c69cad2017-08-21 12:12:51 -07003591 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3592 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003593 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003594 *handle = layer->getHandle();
3595 *gbp = layer->getProducer();
3596 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003597 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003598
David Sodman0c69cad2017-08-21 12:12:51 -07003599 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003600 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003601}
3602
chaviw13fdc492017-06-27 12:40:18 -07003603status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003604 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003605 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003606{
chaviw13fdc492017-06-27 12:40:18 -07003607 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003608 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003609 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003610}
3611
Mathias Agopianac9fa422013-02-11 16:40:36 -08003612status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003613{
Robert Carr9524cb32017-02-13 11:32:32 -08003614 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003615 status_t err = NO_ERROR;
3616 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003617 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003618 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003619 err = removeLayer(l);
3620 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3621 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003622 }
3623 return err;
3624}
3625
Mathias Agopian13127d82013-03-05 17:47:11 -08003626status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003627{
Mathias Agopian67106042013-03-14 19:18:13 -07003628 // called by ~LayerCleaner() when all references to the IBinder (handle)
3629 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003630 sp<Layer> l = layer.promote();
3631 if (l == nullptr) {
3632 // The layer has already been removed, carry on
3633 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003634 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003635 // If we have a parent, then we can continue to live as long as it does.
3636 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003637}
3638
Mathias Agopianb60314a2012-04-10 22:09:54 -07003639// ---------------------------------------------------------------------------
3640
Andy McFadden13a082e2012-08-24 10:16:42 -07003641void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003642 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003643 Vector<ComposerState> state;
3644 Vector<DisplayState> displays;
3645 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003646 d.what = DisplayState::eDisplayProjectionChanged |
3647 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003648 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003649 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003650 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003651 d.frame.makeInvalid();
3652 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003653 d.width = 0;
3654 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003655 displays.add(d);
3656 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003657 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3658 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003659
David Sodman105b7dc2017-11-04 20:28:14 -07003660 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003661 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003662 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003663
Brian Andersond0010582017-03-07 13:20:31 -08003664 // Use phase of 0 since phase is not known.
3665 // Use latency of 0, which will snap to the ideal latency.
3666 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003667}
3668
3669void SurfaceFlinger::initializeDisplays() {
3670 class MessageScreenInitialized : public MessageBase {
3671 SurfaceFlinger* flinger;
3672 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003673 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003674 virtual bool handler() {
3675 flinger->onInitializeDisplays();
3676 return true;
3677 }
3678 };
3679 sp<MessageBase> msg = new MessageScreenInitialized(this);
3680 postMessageAsync(msg); // we may be called from main thread, use async message
3681}
3682
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003683void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003684 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003685 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3686 this);
3687 int32_t type = hw->getDisplayType();
3688 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003689
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003690 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003691 return;
3692 }
3693
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003694 hw->setPowerMode(mode);
3695 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3696 ALOGW("Trying to set power mode for virtual display");
3697 return;
3698 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003699
Lloyd Pique4dccc412018-01-22 17:21:36 -08003700 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003701 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003702 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3703 if (idx < 0) {
3704 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3705 return;
3706 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003707 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003708 }
3709
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003710 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003711 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003712 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003713 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3714 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003715 // FIXME: eventthread only knows about the main display right now
3716 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003717 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003718 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003719
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003720 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003721 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003722 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003723
3724 struct sched_param param = {0};
3725 param.sched_priority = 1;
3726 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3727 ALOGW("Couldn't set SCHED_FIFO on display on");
3728 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003729 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003730 // Turn off the display
3731 struct sched_param param = {0};
3732 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3733 ALOGW("Couldn't set SCHED_OTHER on display off");
3734 }
3735
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003736 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3737 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003738 disableHardwareVsync(true); // also cancels any in-progress resync
3739
Mathias Agopiancde87a32012-09-13 14:09:01 -07003740 // FIXME: eventthread only knows about the main display right now
3741 mEventThread->onScreenReleased();
3742 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003743
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003744 getHwComposer().setPowerMode(type, mode);
3745 mVisibleRegionsDirty = true;
3746 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003747 } else if (mode == HWC_POWER_MODE_DOZE ||
3748 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003749 // Update display while dozing
3750 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003751 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3752 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003753 // FIXME: eventthread only knows about the main display right now
3754 mEventThread->onScreenAcquired();
3755 resyncToHardwareVsync(true);
3756 }
3757 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3758 // Leave display going to doze
3759 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3760 disableHardwareVsync(true); // also cancels any in-progress resync
3761 // FIXME: eventthread only knows about the main display right now
3762 mEventThread->onScreenReleased();
3763 }
3764 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003765 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003766 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003767 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003768 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003769 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003770}
3771
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003772void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3773 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003774 SurfaceFlinger& mFlinger;
3775 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003776 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003777 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003778 MessageSetPowerMode(SurfaceFlinger& flinger,
3779 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3780 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003781 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003782 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003783 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003784 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003785 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003786 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003787 ALOGW("Attempt to set power mode = %d for virtual display",
3788 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003789 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003790 mFlinger.setPowerModeInternal(
3791 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003792 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003793 return true;
3794 }
3795 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003796 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003797 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003798}
3799
3800// ---------------------------------------------------------------------------
3801
Lloyd Pique755e3192018-01-31 16:46:15 -08003802status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3803 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003804 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003805
Mathias Agopianbd115332013-04-18 16:41:04 -07003806 IPCThreadState* ipc = IPCThreadState::self();
3807 const int pid = ipc->getCallingPid();
3808 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003809
Mathias Agopianbd115332013-04-18 16:41:04 -07003810 if ((uid != AID_SHELL) &&
3811 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003812 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003813 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003814 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003815 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003816 // (this would indicate SF is stuck, but we want to be able to
3817 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003818 status_t err = mStateLock.timedLock(s2ns(1));
3819 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003820 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003821 result.appendFormat(
3822 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3823 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003824 }
3825
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003826 bool dumpAll = true;
3827 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003828 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003829
3830 if (asProto) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003831 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviwa3d7bd32017-11-03 09:41:53 -07003832 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3833 dumpAll = false;
3834 }
3835
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003836 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003837 if ((index < numArgs) &&
3838 (args[index] == String16("--list"))) {
3839 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003840 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003841 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003842 }
3843
3844 if ((index < numArgs) &&
3845 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003846 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003847 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003848 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003849 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003850
3851 if ((index < numArgs) &&
3852 (args[index] == String16("--latency-clear"))) {
3853 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003854 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003855 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003856 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003857
3858 if ((index < numArgs) &&
3859 (args[index] == String16("--dispsync"))) {
3860 index++;
3861 mPrimaryDispSync.dump(result);
3862 dumpAll = false;
3863 }
Dan Stozab90cf072015-03-05 11:05:59 -08003864
3865 if ((index < numArgs) &&
3866 (args[index] == String16("--static-screen"))) {
3867 index++;
3868 dumpStaticScreenStats(result);
3869 dumpAll = false;
3870 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003871
3872 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003873 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003874 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003875 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003876 dumpAll = false;
3877 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003878
3879 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3880 index++;
3881 dumpWideColorInfo(result);
3882 dumpAll = false;
3883 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003884
3885 if ((index < numArgs) &&
3886 (args[index] == String16("--enable-layer-stats"))) {
3887 index++;
3888 mLayerStats.enable();
3889 dumpAll = false;
3890 }
3891
3892 if ((index < numArgs) &&
3893 (args[index] == String16("--disable-layer-stats"))) {
3894 index++;
3895 mLayerStats.disable();
3896 dumpAll = false;
3897 }
3898
3899 if ((index < numArgs) &&
3900 (args[index] == String16("--clear-layer-stats"))) {
3901 index++;
3902 mLayerStats.clear();
3903 dumpAll = false;
3904 }
3905
3906 if ((index < numArgs) &&
3907 (args[index] == String16("--dump-layer-stats"))) {
3908 index++;
3909 mLayerStats.dump(result);
3910 dumpAll = false;
3911 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003912 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003913
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003914 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003915 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003916 }
3917
Mathias Agopian9795c422009-08-26 16:36:26 -07003918 if (locked) {
3919 mStateLock.unlock();
3920 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003921 }
3922 write(fd, result.string(), result.size());
3923 return NO_ERROR;
3924}
3925
Dan Stozac7014012014-02-14 15:03:43 -08003926void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3927 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003928{
Robert Carr2047fae2016-11-28 14:09:09 -08003929 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003930 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003931 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003932}
3933
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003934void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003935 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003936{
3937 String8 name;
3938 if (index < args.size()) {
3939 name = String8(args[index]);
3940 index++;
3941 }
3942
David Sodman105b7dc2017-11-04 20:28:14 -07003943 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003944 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003945 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003946
3947 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003948 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003949 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003950 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003951 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003952 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003953 }
Robert Carr2047fae2016-11-28 14:09:09 -08003954 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003955 }
3956}
3957
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003958void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003959 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003960{
3961 String8 name;
3962 if (index < args.size()) {
3963 name = String8(args[index]);
3964 index++;
3965 }
3966
Robert Carr2047fae2016-11-28 14:09:09 -08003967 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003968 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003969 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003970 }
Robert Carr2047fae2016-11-28 14:09:09 -08003971 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003972
Svetoslavd85084b2014-03-20 10:28:31 -07003973 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003974}
3975
Jamie Gennis6547ff42013-07-16 20:12:42 -07003976// This should only be called from the main thread. Otherwise it would need
3977// the lock and should use mCurrentState rather than mDrawingState.
3978void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003979 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003980 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003981 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003982
3983 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3984}
3985
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003986void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003987{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003988 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003989
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003990 if (isLayerTripleBufferingDisabled())
3991 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003992
3993 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003994 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003995 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003996 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003997 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3998 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003999 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004000}
4001
Dan Stozab90cf072015-03-05 11:05:59 -08004002void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4003{
4004 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004005 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4006 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004007 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004008 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004009 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4010 b + 1, bucketTimeSec, percent);
4011 }
David Sodman4a36e932017-11-07 14:29:47 -08004012 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004013 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004014 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004015 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004016 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004017}
4018
Dan Stozae77c7662016-05-13 11:37:28 -07004019void SurfaceFlinger::recordBufferingStats(const char* layerName,
4020 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004021 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4022 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004023 for (const auto& segment : history) {
4024 if (!segment.usedThirdBuffer) {
4025 stats.twoBufferTime += segment.totalTime;
4026 }
4027 if (segment.occupancyAverage < 1.0f) {
4028 stats.doubleBufferedTime += segment.totalTime;
4029 } else if (segment.occupancyAverage < 2.0f) {
4030 stats.tripleBufferedTime += segment.totalTime;
4031 }
4032 ++stats.numSegments;
4033 stats.totalTime += segment.totalTime;
4034 }
4035}
4036
Brian Andersond6927fb2016-07-23 23:37:30 -07004037void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4038 result.appendFormat("Layer frame timestamps:\n");
4039
4040 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4041 const size_t count = currentLayers.size();
4042 for (size_t i=0 ; i<count ; i++) {
4043 currentLayers[i]->dumpFrameEvents(result);
4044 }
4045}
4046
Dan Stozae77c7662016-05-13 11:37:28 -07004047void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4048 result.append("Buffering stats:\n");
4049 result.append(" [Layer name] <Active time> <Two buffer> "
4050 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004051 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004052 typedef std::tuple<std::string, float, float, float> BufferTuple;
4053 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004054 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004055 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004056 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004057 if (stats.numSegments == 0) {
4058 continue;
4059 }
4060 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4061 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4062 stats.totalTime;
4063 float doubleBufferRatio = static_cast<float>(
4064 stats.doubleBufferedTime) / stats.totalTime;
4065 float tripleBufferRatio = static_cast<float>(
4066 stats.tripleBufferedTime) / stats.totalTime;
4067 sorted.insert({activeTime, {name, twoBufferRatio,
4068 doubleBufferRatio, tripleBufferRatio}});
4069 }
4070 for (const auto& sortedPair : sorted) {
4071 float activeTime = sortedPair.first;
4072 const BufferTuple& values = sortedPair.second;
4073 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4074 std::get<0>(values).c_str(), activeTime,
4075 std::get<1>(values), std::get<2>(values),
4076 std::get<3>(values));
4077 }
4078 result.append("\n");
4079}
4080
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004081void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4082 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004083 result.appendFormat("DisplayColorSetting: %d\n", mDisplayColorSetting);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004084
4085 // TODO: print out if wide-color mode is active or not
4086
4087 for (size_t d = 0; d < mDisplays.size(); d++) {
4088 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4089 int32_t hwcId = displayDevice->getHwcDisplayId();
4090 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4091 continue;
4092 }
4093
4094 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004095 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004096 for (auto&& mode : modes) {
4097 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4098 }
4099
Peiyong Lina52f0292018-03-14 17:26:31 -07004100 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004101 result.appendFormat(" Current color mode: %s (%d)\n",
4102 decodeColorMode(currentMode).c_str(), currentMode);
4103 }
4104 result.append("\n");
4105}
4106
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004107LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004108 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004109 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4110 const State& state = useDrawing ? mDrawingState : mCurrentState;
4111 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004112 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004113 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004114 });
4115
4116 return layersProto;
4117}
4118
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004119LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4120 LayersProto layersProto;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004121 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004122
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004123 SizeProto* resolution = layersProto.mutable_resolution();
4124 resolution->set_w(displayDevice->getWidth());
4125 resolution->set_h(displayDevice->getHeight());
4126
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004127 layersProto.set_color_mode(decodeColorMode(displayDevice->getActiveColorMode()));
4128 layersProto.set_color_transform(decodeColorTransform(displayDevice->getColorTransform()));
4129 layersProto.set_global_transform(
4130 static_cast<int32_t>(displayDevice->getOrientationTransform()));
4131
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004132 mDrawingState.traverseInZOrder([&](Layer* layer) {
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004133 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004134 LayerProto* layerProto = layersProto.add_layers();
4135 layer->writeToProto(layerProto, hwcId);
4136 }
4137 });
4138
4139 return layersProto;
4140}
4141
Mathias Agopian74d211a2013-04-22 16:55:35 +02004142void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4143 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004144{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004145 bool colorize = false;
4146 if (index < args.size()
4147 && (args[index] == String16("--color"))) {
4148 colorize = true;
4149 index++;
4150 }
4151
4152 Colorizer colorizer(colorize);
4153
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004154 // figure out if we're stuck somewhere
4155 const nsecs_t now = systemTime();
4156 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4157 const nsecs_t inTransaction(mDebugInTransaction);
4158 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4159 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4160
4161 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004162 * Dump library configuration.
4163 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004164
4165 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004166 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004167 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004168 appendSfConfigString(result);
4169 appendUiConfigString(result);
4170 appendGuiConfigString(result);
4171 result.append("\n");
4172
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004173 result.append("\nWide-Color information:\n");
4174 dumpWideColorInfo(result);
4175
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004176 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004177 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004178 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004179 result.append(SyncFeatures::getInstance().toString());
4180 result.append("\n");
4181
David Sodman105b7dc2017-11-04 20:28:14 -07004182 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004183
Andy McFadden41d67d72014-04-25 16:58:34 -07004184 colorizer.bold(result);
4185 result.append("DispSync configuration: ");
4186 colorizer.reset(result);
Dan Stoza84d619e2018-03-28 17:07:36 -07004187 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, early sf phase %" PRId64
4188 " ns, present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4189 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, mVsyncModulator.getEarlyPhaseOffset(),
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004190 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004191 result.append("\n");
4192
Dan Stozab90cf072015-03-05 11:05:59 -08004193 // Dump static screen stats
4194 result.append("\n");
4195 dumpStaticScreenStats(result);
4196 result.append("\n");
4197
Dan Stozae77c7662016-05-13 11:37:28 -07004198 dumpBufferingStats(result);
4199
Andy McFadden4803b742012-09-24 19:07:20 -07004200 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004201 * Dump the visible layer list
4202 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004203 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004204 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004205 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4206 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004207 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004208
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004209 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004210 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004211 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004212 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004213
4214 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004215 * Dump Display state
4216 */
4217
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004218 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004219 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004220 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004221 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4222 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004223 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004224 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004225 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004226
4227 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004228 * Dump SurfaceFlinger global state
4229 */
4230
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004231 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004232 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004233 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004234
Mathias Agopian888c8222012-08-04 21:10:38 -07004235 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004236 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004237
David Sodmanbc815282017-11-05 18:57:52 -08004238 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004239
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004240 if (hw) {
4241 hw->undefinedRegion.dump(result, "undefinedRegion");
4242 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4243 hw->getOrientation(), hw->isDisplayOn());
4244 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004245 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004246 " last eglSwapBuffers() time: %f us\n"
4247 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004248 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004249 " refresh-rate : %f fps\n"
4250 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004251 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004252 " gpu_to_cpu_unsupported : %d\n"
4253 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004254 mLastSwapBufferTime/1000.0,
4255 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004256 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004257 1e9 / activeConfig->getVsyncPeriod(),
4258 activeConfig->getDpiX(),
4259 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004260 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004261
Mathias Agopian74d211a2013-04-22 16:55:35 +02004262 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004263 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004264
Mathias Agopian74d211a2013-04-22 16:55:35 +02004265 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004266 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004267
4268 /*
4269 * VSYNC state
4270 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004271 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004272 result.append("\n");
4273
4274 /*
4275 * HWC layer minidump
4276 */
4277 for (size_t d = 0; d < mDisplays.size(); d++) {
4278 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4279 int32_t hwcId = displayDevice->getHwcDisplayId();
4280 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4281 continue;
4282 }
4283
4284 result.appendFormat("Display %d HWC layers:\n", hwcId);
4285 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004286 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004287 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004288 });
Dan Stozae22aec72016-08-01 13:20:59 -07004289 result.append("\n");
4290 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004291
4292 /*
4293 * Dump HWComposer state
4294 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004295 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004296 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004297 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004298 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004299 result.appendFormat(" h/w composer %s\n",
4300 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004301 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004302
4303 /*
4304 * Dump gralloc state
4305 */
4306 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4307 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004308
4309 /*
4310 * Dump VrFlinger state if in use.
4311 */
4312 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4313 result.append("VrFlinger state:\n");
4314 result.append(mVrFlinger->Dump().c_str());
4315 result.append("\n");
4316 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004317}
4318
Mathias Agopian13127d82013-03-05 17:47:11 -08004319const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004320SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004321 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004322 wp<IBinder> dpy;
4323 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4324 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4325 dpy = mDisplays.keyAt(i);
4326 break;
4327 }
4328 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004329 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004330 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4331 // Just use the primary display so we have something to return
4332 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4333 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004334 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004335}
4336
Keun young Park63f165f2012-08-31 10:53:36 -07004337bool SurfaceFlinger::startDdmConnection()
4338{
4339 void* libddmconnection_dso =
4340 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4341 if (!libddmconnection_dso) {
4342 return false;
4343 }
4344 void (*DdmConnection_start)(const char* name);
4345 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004346 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004347 if (!DdmConnection_start) {
4348 dlclose(libddmconnection_dso);
4349 return false;
4350 }
4351 (*DdmConnection_start)(getServiceName());
4352 return true;
4353}
4354
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004355status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004356 switch (code) {
4357 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004358 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004359 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004360 case CLEAR_ANIMATION_FRAME_STATS:
4361 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004362 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004363 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004364 case ENABLE_VSYNC_INJECTIONS:
4365 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004366 {
4367 // codes that require permission check
4368 IPCThreadState* ipc = IPCThreadState::self();
4369 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004370 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004371 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004372 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004373 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004374 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004375 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004376 break;
4377 }
Robert Carr1db73f62016-12-21 12:58:51 -08004378 /*
4379 * Calling setTransactionState is safe, because you need to have been
4380 * granted a reference to Client* and Handle* to do anything with it.
4381 *
4382 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4383 */
4384 case SET_TRANSACTION_STATE:
4385 case CREATE_SCOPED_CONNECTION:
4386 {
4387 return OK;
4388 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004389 case CAPTURE_SCREEN:
4390 {
4391 // codes that require permission check
4392 IPCThreadState* ipc = IPCThreadState::self();
4393 const int pid = ipc->getCallingPid();
4394 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004395 if ((uid != AID_GRAPHICS) &&
4396 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004397 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004398 return PERMISSION_DENIED;
4399 }
4400 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004401 }
chaviwa76b2712017-09-20 12:02:26 -07004402 case CAPTURE_LAYERS: {
4403 IPCThreadState* ipc = IPCThreadState::self();
4404 const int pid = ipc->getCallingPid();
4405 const int uid = ipc->getCallingUid();
4406 if ((uid != AID_GRAPHICS) &&
4407 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4408 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4409 return PERMISSION_DENIED;
4410 }
4411 break;
4412 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004413 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004414 return OK;
4415}
4416
4417status_t SurfaceFlinger::onTransact(
4418 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4419{
4420 status_t credentialCheck = CheckTransactCodeCredentials(code);
4421 if (credentialCheck != OK) {
4422 return credentialCheck;
4423 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004424
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004425 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4426 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004427 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004428 IPCThreadState* ipc = IPCThreadState::self();
4429 const int uid = ipc->getCallingUid();
4430 if (CC_UNLIKELY(uid != AID_SYSTEM
4431 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004432 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004433 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004434 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004435 return PERMISSION_DENIED;
4436 }
4437 int n;
4438 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004439 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004440 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004441 return NO_ERROR;
4442 case 1002: // SHOW_UPDATES
4443 n = data.readInt32();
4444 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004445 invalidateHwcGeometry();
4446 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004447 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004448 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004449 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004450 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004451 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004452 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004453 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004454 setTransactionFlags(
4455 eTransactionNeeded|
4456 eDisplayTransactionNeeded|
4457 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004458 return NO_ERROR;
4459 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004460 case 1006:{ // send empty update
4461 signalRefresh();
4462 return NO_ERROR;
4463 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004464 case 1008: // toggle use of hw composer
4465 n = data.readInt32();
4466 mDebugDisableHWC = n ? 1 : 0;
4467 invalidateHwcGeometry();
4468 repaintEverything();
4469 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004470 case 1009: // toggle use of transform hint
4471 n = data.readInt32();
4472 mDebugDisableTransformHint = n ? 1 : 0;
4473 invalidateHwcGeometry();
4474 repaintEverything();
4475 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004476 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004477 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004478 reply->writeInt32(0);
4479 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004480 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004481 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004482 return NO_ERROR;
4483 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004484 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004485 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004486 return NO_ERROR;
4487 }
4488 case 1014: {
4489 // daltonize
4490 n = data.readInt32();
4491 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004492 case 1:
4493 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4494 break;
4495 case 2:
4496 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4497 break;
4498 case 3:
4499 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4500 break;
4501 default:
4502 mDaltonizer.setType(ColorBlindnessType::None);
4503 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004504 }
4505 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004506 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004507 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004508 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004509 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004510 invalidateHwcGeometry();
4511 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004512 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004513 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004514 case 1015: {
4515 // apply a color matrix
4516 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004517 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004518 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004519 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004520 for (size_t j = 0; j < 4; j++) {
4521 mColorMatrix[i][j] = data.readFloat();
4522 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004523 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004524 } else {
4525 mColorMatrix = mat4();
4526 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004527
4528 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4529 // the division by w in the fragment shader
4530 float4 lastRow(transpose(mColorMatrix)[3]);
4531 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4532 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4533 }
4534
Alan Viverette9c5a3332013-09-12 20:04:35 -07004535 invalidateHwcGeometry();
4536 repaintEverything();
4537 return NO_ERROR;
4538 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004539 // This is an experimental interface
4540 // Needs to be shifted to proper binder interface when we productize
4541 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004542 n = data.readInt32();
4543 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004544 return NO_ERROR;
4545 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004546 case 1017: {
4547 n = data.readInt32();
4548 mForceFullDamage = static_cast<bool>(n);
4549 return NO_ERROR;
4550 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004551 case 1018: { // Modify Choreographer's phase offset
4552 n = data.readInt32();
4553 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4554 return NO_ERROR;
4555 }
4556 case 1019: { // Modify SurfaceFlinger's phase offset
4557 n = data.readInt32();
4558 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4559 return NO_ERROR;
4560 }
Irvel468051e2016-06-13 16:44:44 -07004561 case 1020: { // Layer updates interceptor
4562 n = data.readInt32();
4563 if (n) {
4564 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004565 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004566 }
4567 else{
4568 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004569 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004570 }
4571 return NO_ERROR;
4572 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004573 case 1021: { // Disable HWC virtual displays
4574 n = data.readInt32();
4575 mUseHwcVirtualDisplays = !n;
4576 return NO_ERROR;
4577 }
Romain Guy0147a172017-06-01 13:53:56 -07004578 case 1022: { // Set saturation boost
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004579 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004580
4581 invalidateHwcGeometry();
4582 repaintEverything();
4583 return NO_ERROR;
4584 }
Romain Guy54f154a2017-10-24 21:40:32 +01004585 case 1023: { // Set native mode
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004586 int32_t value = data.readInt32();
4587 if (value > 2) {
4588 return BAD_VALUE;
4589 }
4590 if (value == 2 && !mBuiltinDisplaySupportsEnhance) {
4591 return BAD_VALUE;
4592 }
Romain Guy54f154a2017-10-24 21:40:32 +01004593
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004594 mDisplayColorSetting = toDisplayColorSetting(value);
Romain Guy54f154a2017-10-24 21:40:32 +01004595 invalidateHwcGeometry();
4596 repaintEverything();
4597 return NO_ERROR;
4598 }
4599 case 1024: { // Is wide color gamut rendering/color management supported?
4600 reply->writeBool(hasWideColorDisplay);
4601 return NO_ERROR;
4602 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004603 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004604 n = data.readInt32();
4605 if (n) {
4606 ALOGV("LayerTracing enabled");
4607 mTracing.enable();
4608 doTracing("tracing.enable");
4609 reply->writeInt32(NO_ERROR);
4610 } else {
4611 ALOGV("LayerTracing disabled");
4612 status_t err = mTracing.disable();
4613 reply->writeInt32(err);
4614 }
4615 return NO_ERROR;
4616 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004617 case 1026: { // Get layer tracing status
4618 reply->writeBool(mTracing.isEnabled());
4619 return NO_ERROR;
4620 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004621 // Is a DisplayColorSetting supported?
4622 case 1027: {
4623 int32_t value = data.readInt32();
4624 switch (value) {
4625 case 0:
4626 reply->writeBool(hasWideColorDisplay);
4627 return NO_ERROR;
4628 case 1:
4629 reply->writeBool(true);
4630 return NO_ERROR;
4631 case 2:
4632 reply->writeBool(mBuiltinDisplaySupportsEnhance);
4633 return NO_ERROR;
4634 default:
4635 return BAD_VALUE;
4636 }
4637 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004638 }
4639 }
4640 return err;
4641}
4642
Steven Thomas6d8110b2017-08-31 18:24:21 -07004643void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004644 android_atomic_or(1, &mRepaintEverything);
4645 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004646}
4647
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004648// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4649class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004650public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004651 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4652 ~WindowDisconnector() {
4653 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004654 }
4655
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004656private:
4657 ANativeWindow* mWindow;
4658 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004659};
4660
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004661status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4662 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4663 int32_t minLayerZ, int32_t maxLayerZ,
4664 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004665 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004666 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004667
chaviwa76b2712017-09-20 12:02:26 -07004668 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4669
4670 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004671 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4672
chaviwa76b2712017-09-20 12:02:26 -07004673 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4674
4675 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4676 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004677 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004678}
4679
4680status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004681 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004682 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004683 ATRACE_CALL();
4684
4685 class LayerRenderArea : public RenderArea {
4686 public:
Robert Carr578038f2018-03-09 12:25:24 -08004687 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4688 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004689 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004690 mLayer(layer),
4691 mCrop(crop),
4692 mFlinger(flinger),
4693 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004694 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004695 Rect getBounds() const override {
4696 const Layer::State& layerState(mLayer->getDrawingState());
4697 return Rect(layerState.active.w, layerState.active.h);
4698 }
4699 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4700 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4701 bool isSecure() const override { return false; }
4702 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004703 Rect getSourceCrop() const override {
4704 if (mCrop.isEmpty()) {
4705 return getBounds();
4706 } else {
4707 return mCrop;
4708 }
4709 }
4710 bool getWideColorSupport() const override { return false; }
4711 Dataspace getDataSpace() const override { return Dataspace::UNKNOWN; }
Robert Carr578038f2018-03-09 12:25:24 -08004712
4713 class ReparentForDrawing {
4714 public:
4715 const sp<Layer>& oldParent;
4716 const sp<Layer>& newParent;
4717
4718 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4719 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004720 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004721 }
Robert Carr15eae092018-03-23 13:43:53 -07004722 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004723 };
4724
4725 void render(std::function<void()> drawLayers) override {
4726 if (!mChildrenOnly) {
4727 mTransform = mLayer->getTransform().inverse();
4728 drawLayers();
4729 } else {
4730 Rect bounds = getBounds();
4731 screenshotParentLayer =
4732 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4733 bounds.getWidth(), bounds.getHeight(), 0);
4734
4735 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4736 drawLayers();
4737 }
4738 }
chaviwa76b2712017-09-20 12:02:26 -07004739
chaviwa76b2712017-09-20 12:02:26 -07004740 private:
chaviw7206d492017-11-10 16:16:12 -08004741 const sp<Layer> mLayer;
4742 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004743
4744 // In the "childrenOnly" case we reparent the children to a screenshot
4745 // layer which has no properties set and which does not draw.
4746 sp<ContainerLayer> screenshotParentLayer;
4747 Transform mTransform;
4748
4749 SurfaceFlinger* mFlinger;
4750 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004751 };
4752
4753 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4754 auto parent = layerHandle->owner.promote();
4755
chaviw7206d492017-11-10 16:16:12 -08004756 if (parent == nullptr || parent->isPendingRemoval()) {
4757 ALOGE("captureLayers called with a removed parent");
4758 return NAME_NOT_FOUND;
4759 }
4760
Robert Carr578038f2018-03-09 12:25:24 -08004761 const int uid = IPCThreadState::self()->getCallingUid();
4762 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4763 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4764 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4765 return PERMISSION_DENIED;
4766 }
4767
chaviw7206d492017-11-10 16:16:12 -08004768 Rect crop(sourceCrop);
4769 if (sourceCrop.width() <= 0) {
4770 crop.left = 0;
4771 crop.right = parent->getCurrentState().active.w;
4772 }
4773
4774 if (sourceCrop.height() <= 0) {
4775 crop.top = 0;
4776 crop.bottom = parent->getCurrentState().active.h;
4777 }
4778
4779 int32_t reqWidth = crop.width() * frameScale;
4780 int32_t reqHeight = crop.height() * frameScale;
4781
Robert Carr578038f2018-03-09 12:25:24 -08004782 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004783
Robert Carr578038f2018-03-09 12:25:24 -08004784 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004785 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4786 if (!layer->isVisible()) {
4787 return;
Robert Carr578038f2018-03-09 12:25:24 -08004788 } else if (childrenOnly && layer == parent.get()) {
4789 return;
chaviwa76b2712017-09-20 12:02:26 -07004790 }
4791 visitor(layer);
4792 });
4793 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004794 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004795}
4796
4797status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4798 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004799 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004800 bool useIdentityTransform) {
4801 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004802
chaviwa76b2712017-09-20 12:02:26 -07004803 renderArea.updateDimensions();
4804
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004805 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4806 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4807 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4808 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004809
4810 // This mutex protects syncFd and captureResult for communication of the return values from the
4811 // main thread back to this Binder thread
4812 std::mutex captureMutex;
4813 std::condition_variable captureCondition;
4814 std::unique_lock<std::mutex> captureLock(captureMutex);
4815 int syncFd = -1;
4816 std::optional<status_t> captureResult;
4817
Robert Carr03480e22018-01-04 16:02:06 -08004818 const int uid = IPCThreadState::self()->getCallingUid();
4819 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4820
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004821 sp<LambdaMessage> message = new LambdaMessage([&]() {
4822 // If there is a refresh pending, bug out early and tell the binder thread to try again
4823 // after the refresh.
4824 if (mRefreshPending) {
4825 ATRACE_NAME("Skipping screenshot for now");
4826 std::unique_lock<std::mutex> captureLock(captureMutex);
4827 captureResult = std::make_optional<status_t>(EAGAIN);
4828 captureCondition.notify_one();
4829 return;
4830 }
4831
4832 status_t result = NO_ERROR;
4833 int fd = -1;
4834 {
4835 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004836 renderArea.render([&]() {
4837 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4838 useIdentityTransform, forSystem, &fd);
4839 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004840 }
4841
4842 {
4843 std::unique_lock<std::mutex> captureLock(captureMutex);
4844 syncFd = fd;
4845 captureResult = std::make_optional<status_t>(result);
4846 captureCondition.notify_one();
4847 }
4848 });
4849
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004850 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004851 if (result == NO_ERROR) {
4852 captureCondition.wait(captureLock, [&]() { return captureResult; });
4853 while (*captureResult == EAGAIN) {
4854 captureResult.reset();
4855 result = postMessageAsync(message);
4856 if (result != NO_ERROR) {
4857 return result;
4858 }
4859 captureCondition.wait(captureLock, [&]() { return captureResult; });
4860 }
4861 result = *captureResult;
4862 }
4863
4864 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004865 sync_wait(syncFd, -1);
4866 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004867 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004868
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004869 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004870}
4871
chaviwa76b2712017-09-20 12:02:26 -07004872void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4873 TraverseLayersFunction traverseLayers, bool yswap,
4874 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004875 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004876
Lloyd Pique144e1162017-12-20 16:44:52 -08004877 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004878
4879 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004880 const auto raWidth = renderArea.getWidth();
4881 const auto raHeight = renderArea.getHeight();
4882
4883 const auto reqWidth = renderArea.getReqWidth();
4884 const auto reqHeight = renderArea.getReqHeight();
4885 Rect sourceCrop = renderArea.getSourceCrop();
4886
4887 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4888 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004889
Dan Stozac1879002014-05-22 15:59:05 -07004890 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004891 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004892 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004893 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004894 }
4895
4896 // ensure that sourceCrop is inside screen
4897 if (sourceCrop.left < 0) {
4898 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4899 }
chaviwa76b2712017-09-20 12:02:26 -07004900 if (sourceCrop.right > raWidth) {
4901 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004902 }
4903 if (sourceCrop.top < 0) {
4904 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4905 }
chaviwa76b2712017-09-20 12:02:26 -07004906 if (sourceCrop.bottom > raHeight) {
4907 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004908 }
4909
Peiyong Lin34beb7a2018-03-28 11:57:12 -07004910 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004911 if (renderArea.getWideColorSupport()) {
4912 outputDataspace = renderArea.getDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004913 }
4914 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Romain Guy88d37dd2017-05-26 17:57:05 -07004915
Mathias Agopian180f10d2013-04-10 22:55:41 -07004916 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004917 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004918
4919 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004920 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4921 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004922 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004923
chaviw50da5042018-04-09 13:49:37 -07004924 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004925 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07004926 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004927
chaviwa76b2712017-09-20 12:02:26 -07004928 traverseLayers([&](Layer* layer) {
4929 if (filtering) layer->setFiltering(true);
bohu21566132018-03-27 14:36:34 -07004930 layer->draw(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004931 if (filtering) layer->setFiltering(false);
4932 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004933}
4934
chaviwa76b2712017-09-20 12:02:26 -07004935status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4936 TraverseLayersFunction traverseLayers,
4937 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004938 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08004939 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07004940 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004941 ATRACE_CALL();
4942
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004943 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004944
4945 traverseLayers([&](Layer* layer) {
4946 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4947 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004948
Robert Carr03480e22018-01-04 16:02:06 -08004949 // We allow the system server to take screenshots of secure layers for
4950 // use in situations like the Screen-rotation animation and place
4951 // the impetus on WindowManager to not persist them.
4952 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004953 ALOGW("FB is protected: PERMISSION_DENIED");
4954 return PERMISSION_DENIED;
4955 }
4956
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004957 // this binds the given EGLImage as a framebuffer for the
4958 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08004959 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08004960 if (bufferBond.getStatus() != NO_ERROR) {
4961 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004962 return INVALID_OPERATION;
4963 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004964
Dan Stozaabcda352017-06-01 14:37:39 -07004965 // this will in fact render into our dequeued buffer
4966 // via an FBO, which means we didn't have to create
4967 // an EGLSurface and therefore we're not
4968 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004969 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004970
Dan Stozaabcda352017-06-01 14:37:39 -07004971 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08004972 getRenderEngine().finish();
4973 *outSyncFd = -1;
4974
chaviwa76b2712017-09-20 12:02:26 -07004975 const auto reqWidth = renderArea.getReqWidth();
4976 const auto reqHeight = renderArea.getReqHeight();
4977
Dan Stozaabcda352017-06-01 14:37:39 -07004978 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4979 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004980 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004981 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08004982 } else {
4983 base::unique_fd syncFd = getRenderEngine().flush();
4984 if (syncFd < 0) {
4985 getRenderEngine().finish();
4986 }
4987 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07004988 }
4989
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004990 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004991}
4992
Mathias Agopiand5556842013-09-19 17:08:37 -07004993void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07004994 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004995 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004996 for (size_t y = 0; y < h; y++) {
4997 uint32_t const* p = (uint32_t const*)vaddr + y * s;
4998 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004999 if (p[x] != 0xFF000000) return;
5000 }
5001 }
chaviwa76b2712017-09-20 12:02:26 -07005002 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005003
Robert Carr2047fae2016-11-28 14:09:09 -08005004 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005005 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005006 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005007 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5008 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5009 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5010 static_cast<float>(state.color.a));
5011 i++;
5012 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005013 }
5014}
5015
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005016// ---------------------------------------------------------------------------
5017
Dan Stoza412903f2017-04-27 13:42:17 -07005018void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5019 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005020}
5021
Dan Stoza412903f2017-04-27 13:42:17 -07005022void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5023 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005024}
5025
chaviwa76b2712017-09-20 12:02:26 -07005026void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
5027 int32_t maxLayerZ,
5028 const LayerVector::Visitor& visitor) {
5029 // We loop through the first level of layers without traversing,
5030 // as we need to interpret min/max layer Z in the top level Z space.
5031 for (const auto& layer : mDrawingState.layersSortedByZ) {
5032 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5033 continue;
5034 }
5035 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005036 // relative layers are traversed in Layer::traverseInZOrder
5037 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005038 continue;
5039 }
5040 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005041 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5042 return;
5043 }
chaviwa76b2712017-09-20 12:02:26 -07005044 if (!layer->isVisible()) {
5045 return;
5046 }
5047 visitor(layer);
5048 });
5049 }
5050}
5051
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005052}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005053
Chia-I Wu30505fb2018-03-26 16:20:31 -07005054
Mathias Agopian3f844832013-08-07 21:24:32 -07005055#if defined(__gl_h_)
5056#error "don't include gl/gl.h in this file"
5057#endif
5058
5059#if defined(__gl2_h_)
5060#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005061#endif