blob: e12d7ca73d9c074022f0a0b0745bd962ccf44f44 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060040#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070041#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070042#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043
Jamie Gennis1a4d8832012-08-02 20:11:05 -070044#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070045#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080047#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080048#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070049
50#include <ui/GraphicBufferAllocator.h>
51#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080053
Mathias Agopiancde87a32012-09-13 14:09:01 -070054#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080055#include <utils/String8.h>
56#include <utils/String16.h>
57#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070058#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080059#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060
Mathias Agopian921e6ac2012-07-23 23:11:29 -070061#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070062#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063
Robert Carr578038f2018-03-09 12:25:24 -080064#include "BufferLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020065#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080066#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020067#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080068#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080069#include "DdmConnection.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070070#include "DispSync.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "DisplayDevice.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070072#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080073#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
Robert Carr578038f2018-03-09 12:25:24 -080078#include "clz.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Steven Thomasb02664d2017-07-26 18:48:28 -070080#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070081#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070082#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070083#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084
Mathias Agopianff2ed702013-09-01 21:36:12 -070085#include "Effects/Daltonizer.h"
86
Mathias Agopian875d8e12013-06-07 15:35:48 -070087#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070088#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070089
Jiyong Park4b20c2e2017-01-14 19:45:11 +090090#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090091#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090092
chaviw1d044282017-09-27 12:19:28 -070093#include <layerproto/LayerProtoParser.h>
94
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080095#define DISPLAY_COUNT 1
96
Mathias Agopianfee2b462013-07-03 12:34:01 -070097/*
98 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
99 * black pixels.
100 */
101#define DEBUG_SCREENSHOTS false
102
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800103namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700104
Jaesoo Lee43518572017-01-23 19:03:16 +0900105using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900106using namespace android::hardware::configstore::V1_0;
Peiyong Linfd997e02018-03-28 15:29:00 -0700107using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700108using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700109using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700110using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900111
Steven Thomasb02664d2017-07-26 18:48:28 -0700112namespace {
113class ConditionalLock {
114public:
115 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
116 if (lock) {
117 mMutex.lock();
118 }
119 }
120 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
121private:
122 Mutex& mMutex;
123 bool mLocked;
124};
125} // namespace anonymous
126
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800127// ---------------------------------------------------------------------------
128
Mathias Agopian99b49842011-06-27 16:05:52 -0700129const String16 sHardwareTest("android.permission.HARDWARE_TEST");
130const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
131const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
132const String16 sDump("android.permission.DUMP");
133
134// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800135int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
136int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700137int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700138bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800139uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800140bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800141bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800142int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800143// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600144bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700145
Kalle Raitaa099a242017-01-11 11:17:29 -0800146
147std::string getHwcServiceName() {
148 char value[PROPERTY_VALUE_MAX] = {};
149 property_get("debug.sf.hwc_service_name", value, "default");
150 ALOGI("Using HWComposer service: '%s'", value);
151 return std::string(value);
152}
153
154bool useTrebleTestingOverride() {
155 char value[PROPERTY_VALUE_MAX] = {};
156 property_get("debug.sf.treble_testing_override", value, "false");
157 ALOGI("Treble testing override: '%s'", value);
158 return std::string(value) == "true";
159}
160
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800161DisplayColorSetting toDisplayColorSetting(int value) {
162 switch(value) {
163 case 0:
164 return DisplayColorSetting::MANAGED;
165 case 1:
166 return DisplayColorSetting::UNMANAGED;
167 case 2:
168 return DisplayColorSetting::ENHANCED;
169 default:
170 return DisplayColorSetting::MANAGED;
171 }
172}
173
174std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
175 switch(displayColorSetting) {
176 case DisplayColorSetting::MANAGED:
177 return std::string("Natural Mode");
178 case DisplayColorSetting::UNMANAGED:
179 return std::string("Saturated Mode");
180 case DisplayColorSetting::ENHANCED:
181 return std::string("Auto Color Mode");
182 }
183 return std::string("Unknown Display Color Setting");
184}
185
Lloyd Pique09594832018-01-22 17:48:03 -0800186NativeWindowSurface::~NativeWindowSurface() = default;
187
188namespace impl {
189
190class NativeWindowSurface final : public android::NativeWindowSurface {
191public:
192 static std::unique_ptr<android::NativeWindowSurface> create(
193 const sp<IGraphicBufferProducer>& producer) {
194 return std::make_unique<NativeWindowSurface>(producer);
195 }
196
197 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
198 : surface(new Surface(producer, false)) {}
199
200 ~NativeWindowSurface() override = default;
201
202private:
203 sp<ANativeWindow> getNativeWindow() const override { return surface; }
204
205 void preallocateBuffers() override { surface->allocateBuffers(); }
206
207 sp<Surface> surface;
208};
209
210} // namespace impl
211
David Sodmanbc815282017-11-05 18:57:52 -0800212SurfaceFlingerBE::SurfaceFlingerBE()
213 : mHwcServiceName(getHwcServiceName()),
214 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800215 mFrameBuckets(),
216 mTotalTime(0),
217 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800218 mComposerSequenceId(0) {
219}
220
Lloyd Pique2d3ee6d2018-01-17 13:42:24 -0800221SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800222 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800223 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700224 mTransactionPending(false),
225 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700226 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700227 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700228 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800229 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800230 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800231 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800232 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800233 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800234 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700235 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700236 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700237 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700238 mDebugInSwapBuffers(0),
239 mLastSwapBufferTime(0),
240 mDebugInTransaction(0),
241 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700242 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700243 mForceFullDamage(false),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000244 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700245 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700246 mHWVsyncAvailable(false),
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 Pique09594832018-01-22 17:48:03 -0800252 mCreateBufferQueue(&BufferQueue::createBufferQueue),
253 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Pique2d3ee6d2018-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 Stoza2713c302018-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 Pique9123ae52018-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);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700411 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700412 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700413 mCurrentState.displays.add(token, info);
Lloyd Pique4d234852018-01-22 17:21:36 -0800414 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700415 return token;
416}
417
Jesse Hall6c913be2013-08-08 12:15:49 -0700418void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
419 Mutex::Autolock _l(mStateLock);
420
421 ssize_t idx = mCurrentState.displays.indexOfKey(display);
422 if (idx < 0) {
423 ALOGW("destroyDisplay: invalid display token");
424 return;
425 }
426
427 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
428 if (!info.isVirtualDisplay()) {
429 ALOGE("destroyDisplay called for non-virtual display");
430 return;
431 }
Lloyd Pique4d234852018-01-22 17:21:36 -0800432 mInterceptor->saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700433 mCurrentState.displays.removeItemsAt(idx);
434 setTransactionFlags(eDisplayTransactionNeeded);
435}
436
Mathias Agopiane57f2922012-08-09 16:29:12 -0700437sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700438 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700439 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800440 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700441 }
Jesse Hall692c7232012-11-08 15:41:56 -0800442 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700443}
444
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800445void SurfaceFlinger::bootFinished()
446{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700447 if (mStartPropertySetThread->join() != NO_ERROR) {
448 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800449 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800450 const nsecs_t now = systemTime();
451 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000452 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700453
454 // wait patiently for the window manager death
455 const String16 name("window");
456 sp<IBinder> window(defaultServiceManager()->getService(name));
457 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700458 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700459 }
460
Steven Thomas050b2c82017-03-06 11:45:16 -0800461 if (mVrFlinger) {
462 mVrFlinger->OnBootFinished();
463 }
464
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700465 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700466 // formerly we would just kill the process, but we now ask it to exit so it
467 // can choose where to stop the animation.
468 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700469
470 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
471 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
472 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700473
Thierry Strudel2924d012017-08-14 15:19:37 -0700474 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700475 readPersistentProperties();
476 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700477 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800478}
479
Mathias Agopian3f844832013-08-07 21:24:32 -0700480void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700481 class MessageDestroyGLTexture : public MessageBase {
Lloyd Pique144e1162017-12-20 16:44:52 -0800482 RE::RenderEngine& engine;
Mathias Agopian3f844832013-08-07 21:24:32 -0700483 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700484 public:
Lloyd Pique144e1162017-12-20 16:44:52 -0800485 MessageDestroyGLTexture(RE::RenderEngine& engine, uint32_t texture)
486 : engine(engine), texture(texture) {}
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700487 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700488 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700489 return true;
490 }
491 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700492 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700493}
494
Lloyd Piquee83f9312018-02-01 12:53:17 -0800495class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700496public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700497 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000498 const char* name) :
499 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700500 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700501 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000502 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
503 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700504 mDispSync(dispSync),
505 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700506 mVsyncMutex(),
507 mPhaseOffset(phaseOffset),
508 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700509
Lloyd Piquee83f9312018-02-01 12:53:17 -0800510 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700511
Lloyd Piquee83f9312018-02-01 12:53:17 -0800512 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700513 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700514 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000515 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700516 static_cast<DispSync::Callback*>(this));
517 if (err != NO_ERROR) {
518 ALOGE("error registering vsync callback: %s (%d)",
519 strerror(-err), err);
520 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700521 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700522 } else {
523 status_t err = mDispSync->removeEventListener(
524 static_cast<DispSync::Callback*>(this));
525 if (err != NO_ERROR) {
526 ALOGE("error unregistering vsync callback: %s (%d)",
527 strerror(-err), err);
528 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700529 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700530 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700531 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700532 }
533
Lloyd Piquee83f9312018-02-01 12:53:17 -0800534 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700535 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700536 mCallback = callback;
537 }
538
Lloyd Piquee83f9312018-02-01 12:53:17 -0800539 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700540 Mutex::Autolock lock(mVsyncMutex);
541
542 // Normalize phaseOffset to [0, period)
543 auto period = mDispSync->getPeriod();
544 phaseOffset %= period;
545 if (phaseOffset < 0) {
546 // If we're here, then phaseOffset is in (-period, 0). After this
547 // operation, it will be in (0, period)
548 phaseOffset += period;
549 }
550 mPhaseOffset = phaseOffset;
551
552 // If we're not enabled, we don't need to mess with the listeners
553 if (!mEnabled) {
554 return;
555 }
556
Dan Stoza2713c302018-03-28 17:07:36 -0700557 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
558 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700559 if (err != NO_ERROR) {
Dan Stoza2713c302018-03-28 17:07:36 -0700560 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700561 strerror(-err), err);
562 }
563 }
564
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700565private:
566 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800567 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700568 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700569 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700570 callback = mCallback;
571
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700572 if (mTraceVsync) {
573 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700574 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700575 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700576 }
577
Peiyong Lin566a3b42018-01-09 18:22:43 -0800578 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700579 callback->onVSyncEvent(when);
580 }
581 }
582
Tim Murray4a4e4a22016-04-19 16:29:23 +0000583 const char* const mName;
584
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700585 int mValue;
586
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700587 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700588 const String8 mVsyncOnLabel;
589 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700590
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700591 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700592
593 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800594 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700595
596 Mutex mVsyncMutex; // Protects the following
597 nsecs_t mPhaseOffset;
598 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700599};
600
Lloyd Piquee83f9312018-02-01 12:53:17 -0800601class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700602public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800603 InjectVSyncSource() = default;
604 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700605
Lloyd Piquee83f9312018-02-01 12:53:17 -0800606 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700607 std::lock_guard<std::mutex> lock(mCallbackMutex);
608 mCallback = callback;
609 }
610
Lloyd Piquee83f9312018-02-01 12:53:17 -0800611 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700612 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700613 if (mCallback) {
614 mCallback->onVSyncEvent(when);
615 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700616 }
617
Lloyd Piquee83f9312018-02-01 12:53:17 -0800618 void setVSyncEnabled(bool) override {}
619 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700620
621private:
622 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800623 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700624};
625
Wei Wangf9b05ee2017-07-19 20:59:39 -0700626// Do not call property_set on main thread which will be blocked by init
627// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700628void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700629 ALOGI( "SurfaceFlinger's main thread ready to run. "
630 "Initializing graphics H/W...");
631
Thierry Strudel2924d012017-08-14 15:19:37 -0700632 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900633
Steven Thomasb02664d2017-07-26 18:48:28 -0700634 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800635
Steven Thomasb02664d2017-07-26 18:48:28 -0700636 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800637 mEventThreadSource =
638 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
639 true, "app");
640 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(), *this, false,
641 "appEventThread");
642 mSfEventThreadSource =
643 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
644 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800645
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800646 mSFEventThread = std::make_unique<impl::EventThread>(mSfEventThreadSource.get(), *this, true,
647 "sfEventThread");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800648 mEventQueue->setEventThread(mSFEventThread.get());
Dan Stoza2713c302018-03-28 17:07:36 -0700649 mVsyncModulator.setEventThread(mSFEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800650
Steven Thomasb02664d2017-07-26 18:48:28 -0700651 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800652 getBE().mRenderEngine =
653 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
654 hasWideColorDisplay
655 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
656 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800657 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700658
659 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
660 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800661 getBE().mHwc.reset(
662 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700663 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800664 // Process any initial hotplug and resulting display changes.
665 processDisplayHotplugEventsLocked();
666 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
667 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800668
Lloyd Piquefcd86612017-12-14 17:15:36 -0800669 // make the default display GLContext current so that we can create textures
670 // when creating Layers (which may happens before we render something)
671 getDefaultDisplayDeviceLocked()->makeCurrent();
672
Steven Thomas050b2c82017-03-06 11:45:16 -0800673 if (useVrFlinger) {
674 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700675 // This callback is called from the vr flinger dispatch thread. We
676 // need to call signalTransaction(), which requires holding
677 // mStateLock when we're not on the main thread. Acquiring
678 // mStateLock from the vr flinger dispatch thread might trigger a
679 // deadlock in surface flinger (see b/66916578), so post a message
680 // to be handled on the main thread instead.
681 sp<LambdaMessage> message = new LambdaMessage([=]() {
682 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
683 mVrFlingerRequestsDisplay = requestDisplay;
684 signalTransaction();
685 });
686 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800687 };
David Sodman105b7dc2017-11-04 20:28:14 -0700688 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
689 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800690 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800691 if (!mVrFlinger) {
692 ALOGE("Failed to start vrflinger");
693 }
694 }
695
Lloyd Pique0c3a8832018-01-22 17:31:47 -0800696 mEventControlThread = std::make_unique<impl::EventControlThread>(
697 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700698
Mathias Agopian92a979a2012-08-02 18:32:23 -0700699 // initialize our drawing state
700 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700701
Andy McFadden13a082e2012-08-24 10:16:42 -0700702 // set initial conditions (e.g. unblank default device)
703 initializeDisplays();
704
David Sodmanbc815282017-11-05 18:57:52 -0800705 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700706
Wei Wangf9b05ee2017-07-19 20:59:39 -0700707 // Inform native graphics APIs whether the present timestamp is supported:
708 if (getHwComposer().hasCapability(
709 HWC2::Capability::PresentFenceIsNotReliable)) {
710 mStartPropertySetThread = new StartPropertySetThread(false);
711 } else {
712 mStartPropertySetThread = new StartPropertySetThread(true);
713 }
714
715 if (mStartPropertySetThread->Start() != NO_ERROR) {
716 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800717 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800718
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800719 mLegacySrgbSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(HWC_DISPLAY_PRIMARY,
720 Dataspace::SRGB_LINEAR);
721
Dan Stoza9e56aa02015-11-02 13:00:03 -0800722 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700723}
724
Romain Guy11d63f42017-07-20 12:47:14 -0700725void SurfaceFlinger::readPersistentProperties() {
726 char value[PROPERTY_VALUE_MAX];
727
728 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800729 mGlobalSaturationFactor = atof(value);
730 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100731
732 property_get("persist.sys.sf.native_mode", value, "0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800733 mDisplayColorSetting = toDisplayColorSetting(atoi(value));
734 ALOGV("Display Color Setting is set to %s.",
735 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Romain Guy11d63f42017-07-20 12:47:14 -0700736}
737
Mathias Agopiana67e4182012-06-19 17:26:12 -0700738void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800739 // Start boot animation service by setting a property mailbox
740 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700741 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800742 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700743 if (mStartPropertySetThread->join() != NO_ERROR) {
744 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800745 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700746}
747
Mathias Agopian875d8e12013-06-07 15:35:48 -0700748size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800749 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700750}
751
Mathias Agopian875d8e12013-06-07 15:35:48 -0700752size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800753 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700754}
755
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800756// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800757
Jamie Gennis582270d2011-08-17 18:19:00 -0700758bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800759 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800760 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800761 return authenticateSurfaceTextureLocked(bufferProducer);
762}
763
764bool SurfaceFlinger::authenticateSurfaceTextureLocked(
765 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800766 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800767 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800768}
769
Brian Anderson6b376712017-04-04 10:51:39 -0700770status_t SurfaceFlinger::getSupportedFrameTimestamps(
771 std::vector<FrameEvent>* outSupported) const {
772 *outSupported = {
773 FrameEvent::REQUESTED_PRESENT,
774 FrameEvent::ACQUIRE,
775 FrameEvent::LATCH,
776 FrameEvent::FIRST_REFRESH_START,
777 FrameEvent::LAST_REFRESH_START,
778 FrameEvent::GPU_COMPOSITION_DONE,
779 FrameEvent::DEQUEUE_READY,
780 FrameEvent::RELEASE,
781 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700782 ConditionalLock _l(mStateLock,
783 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700784 if (!getHwComposer().hasCapability(
785 HWC2::Capability::PresentFenceIsNotReliable)) {
786 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
787 }
788 return NO_ERROR;
789}
790
Dan Stoza7f7da322014-05-02 15:26:25 -0700791status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
792 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800793 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700794 return BAD_VALUE;
795 }
796
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500797 if (!display.get())
798 return NAME_NOT_FOUND;
799
Jesse Hall692c7232012-11-08 15:41:56 -0800800 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700801 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800802 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700803 type = i;
804 break;
805 }
806 }
807
808 if (type < 0) {
809 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700810 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700811
Mathias Agopian8b736f12012-08-13 17:54:26 -0700812 // TODO: Not sure if display density should handled by SF any longer
813 class Density {
814 static int getDensityFromProperty(char const* propName) {
815 char property[PROPERTY_VALUE_MAX];
816 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800817 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700818 density = atoi(property);
819 }
820 return density;
821 }
822 public:
823 static int getEmuDensity() {
824 return getDensityFromProperty("qemu.sf.lcd_density"); }
825 static int getBuildDensity() {
826 return getDensityFromProperty("ro.sf.lcd_density"); }
827 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700828
Dan Stoza7f7da322014-05-02 15:26:25 -0700829 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700830
Steven Thomas6d8110b2017-08-31 18:24:21 -0700831 ConditionalLock _l(mStateLock,
832 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800833 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700834 DisplayInfo info = DisplayInfo();
835
Dan Stoza9e56aa02015-11-02 13:00:03 -0800836 float xdpi = hwConfig->getDpiX();
837 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700838
839 if (type == DisplayDevice::DISPLAY_PRIMARY) {
840 // The density of the device is provided by a build property
841 float density = Density::getBuildDensity() / 160.0f;
842 if (density == 0) {
843 // the build doesn't provide a density -- this is wrong!
844 // use xdpi instead
845 ALOGE("ro.sf.lcd_density must be defined as a build property");
846 density = xdpi / 160.0f;
847 }
848 if (Density::getEmuDensity()) {
849 // if "qemu.sf.lcd_density" is specified, it overrides everything
850 xdpi = ydpi = density = Density::getEmuDensity();
851 density /= 160.0f;
852 }
853 info.density = density;
854
855 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700856 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800857 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700858 } else {
859 // TODO: where should this value come from?
860 static const int TV_DENSITY = 213;
861 info.density = TV_DENSITY / 160.0f;
862 info.orientation = 0;
863 }
864
Dan Stoza9e56aa02015-11-02 13:00:03 -0800865 info.w = hwConfig->getWidth();
866 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700867 info.xdpi = xdpi;
868 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800869 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900870 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800871
Andy McFadden91b2ca82014-06-13 14:04:23 -0700872 // This is how far in advance a buffer must be queued for
873 // presentation at a given time. If you want a buffer to appear
874 // on the screen at time N, you must submit the buffer before
875 // (N - presentationDeadline).
876 //
877 // Normally it's one full refresh period (to give SF a chance to
878 // latch the buffer), but this can be reduced by configuring a
879 // DispSync offset. Any additional delays introduced by the hardware
880 // composer or panel must be accounted for here.
881 //
882 // We add an additional 1ms to allow for processing time and
883 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800884 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800885 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700886
887 // All non-virtual displays are currently considered secure.
888 info.secure = true;
889
Michael Wright28f24d02016-07-12 13:30:53 -0700890 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700891 }
892
Dan Stoza7f7da322014-05-02 15:26:25 -0700893 return NO_ERROR;
894}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700895
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800896status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700897 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800898 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700899 return BAD_VALUE;
900 }
901
902 // FIXME for now we always return stats for the primary display
903 memset(stats, 0, sizeof(*stats));
904 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
905 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
906 return NO_ERROR;
907}
908
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700909int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800910 if (display == nullptr) {
911 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800912 return BAD_VALUE;
913 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700914
915 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800916 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700917 return device->getActiveConfig();
918 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700919
Dan Stoza24a42e92015-03-09 10:04:11 -0700920 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700921}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700922
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700923void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
924 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
925 this);
926 int32_t type = hw->getDisplayType();
927 int currentMode = hw->getActiveConfig();
928
929 if (mode == currentMode) {
930 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
931 return;
932 }
933
934 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
935 ALOGW("Trying to set config for virtual display");
936 return;
937 }
938
939 hw->setActiveConfig(mode);
940 getHwComposer().setActiveConfig(type, mode);
941}
942
943status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
944 class MessageSetActiveConfig: public MessageBase {
945 SurfaceFlinger& mFlinger;
946 sp<IBinder> mDisplay;
947 int mMode;
948 public:
949 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
950 int mode) :
951 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
952 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700953 Vector<DisplayInfo> configs;
954 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700955 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700956 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700957 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700958 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700959 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700960 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800961 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700962 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700963 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700964 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
965 ALOGW("Attempt to set active config = %d for virtual display",
966 mMode);
967 } else {
968 mFlinger.setActiveConfigInternal(hw, mMode);
969 }
970 return true;
971 }
972 };
973 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
974 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700975 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700976}
Michael Wright28f24d02016-07-12 13:30:53 -0700977status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -0700978 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700979 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
980 return BAD_VALUE;
981 }
982
983 if (!display.get()) {
984 return NAME_NOT_FOUND;
985 }
986
987 int32_t type = NAME_NOT_FOUND;
988 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
989 if (display == mBuiltinDisplays[i]) {
990 type = i;
991 break;
992 }
993 }
994
995 if (type < 0) {
996 return type;
997 }
998
Peiyong Lina52f0292018-03-14 17:26:31 -0700999 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001000 {
1001 ConditionalLock _l(mStateLock,
1002 std::this_thread::get_id() != mMainThreadId);
1003 modes = getHwComposer().getColorModes(type);
1004 }
Michael Wright28f24d02016-07-12 13:30:53 -07001005 outColorModes->clear();
1006 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1007
1008 return NO_ERROR;
1009}
1010
Peiyong Lina52f0292018-03-14 17:26:31 -07001011ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001012 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -07001013 if (device != nullptr) {
1014 return device->getActiveColorMode();
1015 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001016 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001017}
1018
1019void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001020 ColorMode mode, Dataspace dataSpace) {
Michael Wright28f24d02016-07-12 13:30:53 -07001021 int32_t type = hw->getDisplayType();
Peiyong Lina52f0292018-03-14 17:26:31 -07001022 ColorMode currentMode = hw->getActiveColorMode();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001023 Dataspace currentDataSpace = hw->getCompositionDataSpace();
Peiyong Lin38e9a562018-04-10 16:24:20 -07001024 RenderIntent currentRenderIntent = hw->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001025
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001026 // Natural Mode means it's color managed and the color must be right,
1027 // thus we pick RenderIntent::COLORIMETRIC as render intent.
1028 // Native Mode means the display is not color managed, and whichever
1029 // render intent is picked doesn't matter, thus return
1030 // RenderIntent::COLORIMETRIC as default here.
1031 RenderIntent renderIntent = RenderIntent::COLORIMETRIC;
1032
1033 // In Auto Color Mode, we want to strech to panel color space, right now
1034 // only the built-in display supports it.
1035 if (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
1036 mBuiltinDisplaySupportsEnhance &&
1037 hw->getDisplayType() == DisplayDevice::DISPLAY_PRIMARY) {
1038 renderIntent = RenderIntent::ENHANCE;
1039 }
Peiyong Lin38e9a562018-04-10 16:24:20 -07001040
1041 if (mode == currentMode && dataSpace == currentDataSpace &&
1042 renderIntent == currentRenderIntent) {
1043 return;
1044 }
1045
1046 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1047 ALOGW("Trying to set config for virtual display");
1048 return;
1049 }
1050
1051 hw->setActiveColorMode(mode);
1052 hw->setCompositionDataSpace(dataSpace);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001053 hw->setActiveRenderIntent(renderIntent);
1054 getHwComposer().setActiveColorMode(type, mode, renderIntent);
1055
1056 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
1057 decodeColorMode(mode).c_str(), mode,
1058 decodeRenderIntent(renderIntent).c_str(), renderIntent,
1059 hw->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001060}
1061
1062
1063status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001064 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -07001065 class MessageSetActiveColorMode: public MessageBase {
1066 SurfaceFlinger& mFlinger;
1067 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -07001068 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001069 public:
1070 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -07001071 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -07001072 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1073 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -07001074 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001075 mFlinger.getDisplayColorModes(mDisplay, &modes);
1076 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -07001077 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001078 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1079 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001080 return true;
1081 }
1082 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1083 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001084 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1085 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001086 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001087 ALOGW("Attempt to set active color mode %s %d for virtual display",
1088 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001089 } else {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001090 mFlinger.setActiveColorModeInternal(hw, mMode, Dataspace::UNKNOWN);
Michael Wright28f24d02016-07-12 13:30:53 -07001091 }
1092 return true;
1093 }
1094 };
1095 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1096 postMessageSync(msg);
1097 return NO_ERROR;
1098}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001099
Svetoslavd85084b2014-03-20 10:28:31 -07001100status_t SurfaceFlinger::clearAnimationFrameStats() {
1101 Mutex::Autolock _l(mStateLock);
1102 mAnimFrameTracker.clearStats();
1103 return NO_ERROR;
1104}
1105
1106status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1107 Mutex::Autolock _l(mStateLock);
1108 mAnimFrameTracker.getStats(outStats);
1109 return NO_ERROR;
1110}
1111
Dan Stozac4f471e2016-03-24 09:31:08 -07001112status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1113 HdrCapabilities* outCapabilities) const {
1114 Mutex::Autolock _l(mStateLock);
1115
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001116 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001117 if (displayDevice == nullptr) {
1118 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1119 return BAD_VALUE;
1120 }
1121
Peiyong Lin62665892018-04-16 11:07:44 -07001122 HdrCapabilities capabilities;
1123 int status = getBE().mHwc->getHdrCapabilities(
1124 displayDevice->getHwcDisplayId(), &capabilities);
1125 if (status == NO_ERROR) {
Peiyong Linf59a7192018-04-25 11:19:31 -07001126 if (displayDevice->hasWideColorGamut()) {
Peiyong Lin62665892018-04-16 11:07:44 -07001127 std::vector<Hdr> types = capabilities.getSupportedHdrTypes();
Peiyong Linf59a7192018-04-25 11:19:31 -07001128 // insert HDR10/HLG as we will force client composition for HDR10/HLG
1129 // layers
1130 if (!displayDevice->hasHDR10Support()) {
1131 types.push_back(Hdr::HDR10);
1132 }
1133 if (!displayDevice->hasHLGSupport()) {
1134 types.push_back(Hdr::HLG);
1135 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001136
1137 *outCapabilities = HdrCapabilities(types,
Peiyong Lin62665892018-04-16 11:07:44 -07001138 capabilities.getDesiredMaxLuminance(),
1139 capabilities.getDesiredMaxAverageLuminance(),
1140 capabilities.getDesiredMinLuminance());
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001141 } else {
Peiyong Lin62665892018-04-16 11:07:44 -07001142 *outCapabilities = std::move(capabilities);
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001143 }
Dan Stozac4f471e2016-03-24 09:31:08 -07001144 } else {
1145 return BAD_VALUE;
1146 }
1147
1148 return NO_ERROR;
1149}
1150
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001151status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001152 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1153 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001154
Chia-I Wu90f669f2017-10-05 14:24:41 -07001155 if (mInjectVSyncs == enable) {
1156 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001157 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001158
1159 if (enable) {
1160 ALOGV("VSync Injections enabled");
1161 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001162 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique0fcde1b2017-12-20 16:50:21 -08001163 mInjectorEventThread =
1164 std::make_unique<impl::EventThread>(mVSyncInjector.get(), *this, false,
1165 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001166 }
Lloyd Pique9123ae52018-01-22 17:14:00 -08001167 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001168 } else {
1169 ALOGV("VSync Injections disabled");
Lloyd Pique9123ae52018-01-22 17:14:00 -08001170 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001171 }
1172
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001173 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001174 });
1175 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001176 return NO_ERROR;
1177}
1178
1179status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001180 Mutex::Autolock _l(mStateLock);
1181
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001182 if (!mInjectVSyncs) {
1183 ALOGE("VSync Injections not enabled");
1184 return BAD_VALUE;
1185 }
1186 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1187 ALOGV("Injecting VSync inside SurfaceFlinger");
1188 mVSyncInjector->onInjectSyncEvent(when);
1189 }
1190 return NO_ERROR;
1191}
1192
Lloyd Pique755e3192018-01-31 16:46:15 -08001193status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1194 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001195 IPCThreadState* ipc = IPCThreadState::self();
1196 const int pid = ipc->getCallingPid();
1197 const int uid = ipc->getCallingUid();
1198 if ((uid != AID_SHELL) &&
1199 !PermissionCache::checkPermission(sDump, pid, uid)) {
1200 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1201 return PERMISSION_DENIED;
1202 }
1203
1204 // Try to acquire a lock for 1s, fail gracefully
1205 const status_t err = mStateLock.timedLock(s2ns(1));
1206 const bool locked = (err == NO_ERROR);
1207 if (!locked) {
1208 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1209 return TIMED_OUT;
1210 }
1211
1212 outLayers->clear();
1213 mCurrentState.traverseInZOrder([&](Layer* layer) {
1214 outLayers->push_back(layer->getLayerDebugInfo());
1215 });
1216
1217 mStateLock.unlock();
1218 return NO_ERROR;
1219}
1220
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001221// ----------------------------------------------------------------------------
1222
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001223sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1224 ISurfaceComposer::VsyncSource vsyncSource) {
1225 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1226 return mSFEventThread->createEventConnection();
1227 } else {
1228 return mEventThread->createEventConnection();
1229 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001230}
1231
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001232// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001233
1234void SurfaceFlinger::waitForEvent() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001235 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001236}
1237
1238void SurfaceFlinger::signalTransaction() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001239 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001240}
1241
1242void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001243 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001244}
1245
1246void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001247 mRefreshPending = true;
Lloyd Pique9123ae52018-01-22 17:14:00 -08001248 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001249}
1250
1251status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001252 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001253 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001254}
1255
1256status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001257 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001258 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001259 if (res == NO_ERROR) {
1260 msg->wait();
1261 }
1262 return res;
1263}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001264
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001265void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001266 do {
1267 waitForEvent();
1268 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001269}
1270
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001271void SurfaceFlinger::enableHardwareVsync() {
1272 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001273 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001274 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001275 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1276 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001277 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001278 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001279}
1280
Jesse Hall948fe0c2013-10-14 12:56:09 -07001281void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001282 Mutex::Autolock _l(mHWVsyncLock);
1283
Jesse Hall948fe0c2013-10-14 12:56:09 -07001284 if (makeAvailable) {
1285 mHWVsyncAvailable = true;
1286 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001287 // Hardware vsync is not currently available, so abort the resync
1288 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001289 return;
1290 }
1291
David Sodman105b7dc2017-11-04 20:28:14 -07001292 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001293 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001294
1295 mPrimaryDispSync.reset();
1296 mPrimaryDispSync.setPeriod(period);
1297
1298 if (!mPrimaryHWVsyncEnabled) {
1299 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001300 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1301 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001302 mPrimaryHWVsyncEnabled = true;
1303 }
1304}
1305
Jesse Hall948fe0c2013-10-14 12:56:09 -07001306void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001307 Mutex::Autolock _l(mHWVsyncLock);
1308 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001309 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1310 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001311 mPrimaryDispSync.endResync();
1312 mPrimaryHWVsyncEnabled = false;
1313 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001314 if (makeUnavailable) {
1315 mHWVsyncAvailable = false;
1316 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001317}
1318
Tim Murray4a4e4a22016-04-19 16:29:23 +00001319void SurfaceFlinger::resyncWithRateLimit() {
1320 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001321
1322 // No explicit locking is needed here since EventThread holds a lock while calling this method
1323 static nsecs_t sLastResyncAttempted = 0;
1324 const nsecs_t now = systemTime();
1325 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001326 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001327 }
Dan Stoza57164302017-05-08 14:03:54 -07001328 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001329}
1330
Steven Thomasb02664d2017-07-26 18:48:28 -07001331void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1332 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001333 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001334 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001335 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001336 return;
1337 }
1338
1339 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001340 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001341 return;
1342 }
1343
Jamie Gennisd1700752013-10-14 12:22:52 -07001344 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001345
Jamie Gennisd1700752013-10-14 12:22:52 -07001346 { // Scope for the lock
1347 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001348 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001349 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001350 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001351 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001352
1353 if (needsHwVsync) {
1354 enableHardwareVsync();
1355 } else {
1356 disableHardwareVsync(false);
1357 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001358}
1359
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001360void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001361 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1362 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001363}
1364
Lloyd Pique715a2c12017-12-14 17:18:08 -08001365void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1366 HWC2::Connection connection) {
1367 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1368 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001369
Lloyd Piqueba04e622017-12-14 17:11:26 -08001370 // Ignore events that do not have the right sequenceId.
1371 if (sequenceId != getBE().mComposerSequenceId) {
1372 return;
1373 }
1374
Steven Thomasb02664d2017-07-26 18:48:28 -07001375 // Only lock if we're not on the main thread. This function is normally
1376 // called on a hwbinder thread, but for the primary display it's called on
1377 // the main thread with the state lock already held, so don't attempt to
1378 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001379 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001380
Lloyd Pique715a2c12017-12-14 17:18:08 -08001381 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001382
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001383 if (std::this_thread::get_id() == mMainThreadId) {
1384 // Process all pending hot plug events immediately if we are on the main thread.
1385 processDisplayHotplugEventsLocked();
1386 }
1387
Lloyd Piqueba04e622017-12-14 17:11:26 -08001388 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001389}
1390
Steven Thomasb02664d2017-07-26 18:48:28 -07001391void SurfaceFlinger::onRefreshReceived(int sequenceId,
1392 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001393 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001394 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001395 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001396 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001397 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001398}
1399
Dan Stoza9e56aa02015-11-02 13:00:03 -08001400void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001401 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001402 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001403 getHwComposer().setVsyncEnabled(disp,
1404 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001405}
1406
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001407// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001408void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001409 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001410 // Clear the drawing state so that the logic inside of
1411 // handleTransactionLocked will fire. It will determine the delta between
1412 // mCurrentState and mDrawingState and re-apply all changes when we make the
1413 // transition.
1414 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001415 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001416 mDisplays.clear();
1417}
1418
Steven Thomas050b2c82017-03-06 11:45:16 -08001419void SurfaceFlinger::updateVrFlinger() {
1420 if (!mVrFlinger)
1421 return;
1422 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001423 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001424 return;
1425 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001426
David Sodman105b7dc2017-11-04 20:28:14 -07001427 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001428 ALOGE("Vr flinger is only supported for remote hardware composer"
1429 " service connections. Ignoring request to transition to vr"
1430 " flinger.");
1431 mVrFlingerRequestsDisplay = false;
1432 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001433 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001434
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001435 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001436
Steven Thomasb02664d2017-07-26 18:48:28 -07001437 int currentDisplayPowerMode = getDisplayDeviceLocked(
1438 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001439
Steven Thomasb02664d2017-07-26 18:48:28 -07001440 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001441 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001442 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001443
Steven Thomasb02664d2017-07-26 18:48:28 -07001444 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001445 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001446 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1447 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001448 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001449
David Sodman105b7dc2017-11-04 20:28:14 -07001450 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1451 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001452
1453 if (vrFlingerRequestsDisplay) {
1454 mVrFlinger->GrantDisplayOwnership();
1455 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001456 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001457 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001458
1459 mVisibleRegionsDirty = true;
1460 invalidateHwcGeometry();
1461
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001462 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001463 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1464 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1465 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001466
Steven Thomasb02664d2017-07-26 18:48:28 -07001467 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001468 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001469 const nsecs_t period = activeConfig->getVsyncPeriod();
1470 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001471
Steven Thomasb02664d2017-07-26 18:48:28 -07001472 // Use phase of 0 since phase is not known.
1473 // Use latency of 0, which will snap to the ideal latency.
1474 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001475
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001476 android_atomic_or(1, &mRepaintEverything);
1477 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001478}
1479
Mathias Agopian4fec8732012-06-29 14:12:52 -07001480void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001481 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001482 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001483 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001484 bool frameMissed = !mHadClientComposition &&
1485 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001486 (mPreviousPresentFence->getSignalTime() ==
1487 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001488 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001489 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001490 signalLayerUpdate();
1491 break;
1492 }
1493
Steven Thomas050b2c82017-03-06 11:45:16 -08001494 // Now that we're going to make it to the handleMessageTransaction()
1495 // call below it's safe to call updateVrFlinger(), which will
1496 // potentially trigger a display handoff.
1497 updateVrFlinger();
1498
Dan Stoza6b9454d2014-11-07 16:00:59 -08001499 bool refreshNeeded = handleMessageTransaction();
1500 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001501 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001502 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001503 // Signal a refresh if a transaction modified the window state,
1504 // a new buffer was latched, or if HWC has requested a full
1505 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001506 signalRefresh();
1507 }
1508 break;
1509 }
1510 case MessageQueue::REFRESH: {
1511 handleMessageRefresh();
1512 break;
1513 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001514 }
1515}
1516
Dan Stoza6b9454d2014-11-07 16:00:59 -08001517bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001518 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001519 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001520 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001521 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001522 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001523 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001524}
1525
Dan Stoza6b9454d2014-11-07 16:00:59 -08001526bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001527 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001528 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001529}
1530
1531void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001532 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001533
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001534 mRefreshPending = false;
1535
Pablo Ceballos40845df2016-01-25 17:41:15 -08001536 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001537
Brian Andersond6927fb2016-07-23 23:37:30 -07001538 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001539 rebuildLayerStacks();
1540 setUpHWComposer();
1541 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001542 doTracing("handleRefresh");
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001543 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001544 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001545 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001546
David Sodman105b7dc2017-11-04 20:28:14 -07001547 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001548
1549 mHadClientComposition = false;
1550 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1551 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1552 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001553 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001554 }
Dan Stoza2713c302018-03-28 17:07:36 -07001555 mVsyncModulator.setLastFrameUsedRenderEngine(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001556
Dan Stoza9e56aa02015-11-02 13:00:03 -08001557 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001558}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001559
Mathias Agopiancd60f992012-08-16 16:28:27 -07001560void SurfaceFlinger::doDebugFlashRegions()
1561{
1562 // is debugging enabled
1563 if (CC_LIKELY(!mDebugRegion))
1564 return;
1565
1566 const bool repaintEverything = mRepaintEverything;
1567 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1568 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001569 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001570 // transform the dirty region into this screen's coordinate space
1571 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1572 if (!dirtyRegion.isEmpty()) {
1573 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001574 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001575
1576 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001577 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001578 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001579 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1580
Mathias Agopianda27af92012-09-13 18:17:13 -07001581 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001582 }
1583 }
1584 }
1585
1586 postFramebuffer();
1587
1588 if (mDebugRegion > 1) {
1589 usleep(mDebugRegion * 1000);
1590 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001591
Dan Stoza9e56aa02015-11-02 13:00:03 -08001592 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001593 auto& displayDevice = mDisplays[displayId];
1594 if (!displayDevice->isDisplayOn()) {
1595 continue;
1596 }
1597
David Sodman105b7dc2017-11-04 20:28:14 -07001598 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1599 ALOGE_IF(result != NO_ERROR,
1600 "prepareFrame for display %zd failed:"
1601 " %d (%s)",
1602 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001603 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001604}
1605
Adrian Roos1e1a1282017-11-01 19:05:31 +01001606void SurfaceFlinger::doTracing(const char* where) {
1607 ATRACE_CALL();
1608 ATRACE_NAME(where);
1609 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001610 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001611 }
1612}
1613
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001614void SurfaceFlinger::logLayerStats() {
1615 ATRACE_CALL();
1616 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1617 int32_t hwcId = -1;
1618 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1619 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1620 if (displayDevice->isPrimary()) {
1621 hwcId = displayDevice->getHwcDisplayId();
1622 break;
1623 }
1624 }
1625 if (hwcId < 0) {
1626 ALOGE("LayerStats: Hmmm, no primary display?");
1627 return;
1628 }
1629 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1630 }
1631}
1632
Brian Andersond6927fb2016-07-23 23:37:30 -07001633void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001634{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001635 ATRACE_CALL();
1636 ALOGV("preComposition");
1637
Mathias Agopiancd60f992012-08-16 16:28:27 -07001638 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001639 mDrawingState.traverseInZOrder([&](Layer* layer) {
1640 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001641 needExtraInvalidate = true;
1642 }
Robert Carr2047fae2016-11-28 14:09:09 -08001643 });
1644
Mathias Agopiancd60f992012-08-16 16:28:27 -07001645 if (needExtraInvalidate) {
1646 signalLayerUpdate();
1647 }
1648}
1649
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001650void SurfaceFlinger::updateCompositorTiming(
1651 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1652 std::shared_ptr<FenceTime>& presentFenceTime) {
1653 // Update queue of past composite+present times and determine the
1654 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001655 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001656 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001657 while (!getBE().mCompositePresentTimes.empty()) {
1658 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001659 // Cached values should have been updated before calling this method,
1660 // which helps avoid duplicate syscalls.
1661 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1662 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1663 break;
1664 }
1665 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001666 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001667 }
1668
1669 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001670 while (getBE().mCompositePresentTimes.size() > 16) {
1671 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001672 }
1673
Brian Andersond0010582017-03-07 13:20:31 -08001674 setCompositorTimingSnapped(
1675 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1676}
1677
1678void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1679 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001680 // Integer division and modulo round toward 0 not -inf, so we need to
1681 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001682 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001683 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1684 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1685
Brian Andersond0010582017-03-07 13:20:31 -08001686 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1687 if (idealLatency <= 0) {
1688 idealLatency = vsyncInterval;
1689 }
1690
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001691 // Snap the latency to a value that removes scheduling jitter from the
1692 // composition and present times, which often have >1ms of jitter.
1693 // Reducing jitter is important if an app attempts to extrapolate
1694 // something (such as user input) to an accurate diasplay time.
1695 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1696 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001697 nsecs_t bias = vsyncInterval / 2;
1698 int64_t extraVsyncs =
1699 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1700 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1701 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001702
David Sodman99974d22017-11-28 12:04:33 -08001703 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1704 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1705 getBE().mCompositorTiming.interval = vsyncInterval;
1706 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001707}
1708
1709void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001710{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001711 ATRACE_CALL();
1712 ALOGV("postComposition");
1713
Brian Anderson3546a3f2016-07-14 11:51:14 -07001714 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001715 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001716 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001717 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001718 }
1719
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001720 // |mStateLock| not needed as we are on the main thread
1721 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001722
David Sodman73beded2017-11-15 11:56:06 -08001723 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001724 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001725 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001726 glCompositionDoneFenceTime =
1727 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001728 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001729 } else {
1730 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1731 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001732
David Sodman73beded2017-11-15 11:56:06 -08001733 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001734 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001735 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001736 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001737
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001738 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1739 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1740
1741 // We use the refreshStartTime which might be sampled a little later than
1742 // when we started doing work for this frame, but that should be okay
1743 // since updateCompositorTiming has snapping logic.
1744 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001745 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001746 CompositorTiming compositorTiming;
1747 {
David Sodman99974d22017-11-28 12:04:33 -08001748 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1749 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001750 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001751
Robert Carr2047fae2016-11-28 14:09:09 -08001752 mDrawingState.traverseInZOrder([&](Layer* layer) {
1753 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001754 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001755 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001756 recordBufferingStats(layer->getName().string(),
1757 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001758 }
Robert Carr2047fae2016-11-28 14:09:09 -08001759 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001760
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001761 if (presentFenceTime->isValid()) {
1762 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001763 enableHardwareVsync();
1764 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001765 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001766 }
1767 }
1768
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001769 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001770 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001771 enableHardwareVsync();
1772 }
1773 }
1774
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001775 if (mAnimCompositionPending) {
1776 mAnimCompositionPending = false;
1777
Brian Anderson4e606e32017-03-16 15:34:57 -07001778 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001779 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001780 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001781 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001782 // The HWC doesn't support present fences, so use the refresh
1783 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001784 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001785 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001786 mAnimFrameTracker.setActualPresentTime(presentTime);
1787 }
1788 mAnimFrameTracker.advanceFrame();
1789 }
Dan Stozab90cf072015-03-05 11:05:59 -08001790
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001791 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1792 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001793 return;
1794 }
1795
1796 nsecs_t currentTime = systemTime();
1797 if (mHasPoweredOff) {
1798 mHasPoweredOff = false;
1799 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001800 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001801 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001802 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1803 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001804 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001805 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001806 }
David Sodman4a36e932017-11-07 14:29:47 -08001807 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001808 }
David Sodman4a36e932017-11-07 14:29:47 -08001809 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001810}
1811
1812void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001813 ATRACE_CALL();
1814 ALOGV("rebuildLayerStacks");
1815
Mathias Agopiancd60f992012-08-16 16:28:27 -07001816 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001817 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001818 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001819 mVisibleRegionsDirty = false;
1820 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001821
Jeff Sharkey76488112017-02-27 14:15:18 -07001822 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1823 Region opaqueRegion;
1824 Region dirtyRegion;
1825 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001826 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001827 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1828 const Transform& tr(displayDevice->getTransform());
1829 const Rect bounds(displayDevice->getBounds());
1830 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001831 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001832
Jeff Sharkey76488112017-02-27 14:15:18 -07001833 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001834 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001835 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1836 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001837 Region drawRegion(tr.transform(
1838 layer->visibleNonTransparentRegion));
1839 drawRegion.andSelf(bounds);
1840 if (!drawRegion.isEmpty()) {
1841 layersSortedByZ.add(layer);
1842 } else {
1843 // Clear out the HWC layer if this layer was
1844 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001845 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001846 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001847 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001848 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001849 // WM changes displayDevice->layerStack upon sleep/awake.
1850 // Here we make sure we delete the HWC layers even if
1851 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001852 hwcLayerDestroyed = layer->destroyHwcLayer(
1853 displayDevice->getHwcDisplayId());
1854 }
1855
1856 // If a layer is not going to get a release fence because
1857 // it is invisible, but it is also going to release its
1858 // old buffer, add it to the list of layers needing
1859 // fences.
1860 if (hwcLayerDestroyed) {
1861 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1862 mLayersWithQueuedFrames.cend(), layer);
1863 if (found != mLayersWithQueuedFrames.cend()) {
1864 layersNeedingFences.add(layer);
1865 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001866 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001867 });
1868 }
1869 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001870 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001871 displayDevice->undefinedRegion.set(bounds);
1872 displayDevice->undefinedRegion.subtractSelf(
1873 tr.transform(opaqueRegion));
1874 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001875 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001876 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001877}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001878
Romain Guy0147a172017-06-01 13:53:56 -07001879mat4 SurfaceFlinger::computeSaturationMatrix() const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001880 if (mGlobalSaturationFactor == 1.0f) {
Romain Guy0147a172017-06-01 13:53:56 -07001881 return mat4();
1882 }
1883
1884 // Rec.709 luma coefficients
1885 float3 luminance{0.213f, 0.715f, 0.072f};
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001886 luminance *= 1.0f - mGlobalSaturationFactor;
Romain Guy0147a172017-06-01 13:53:56 -07001887 return mat4(
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001888 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
1889 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
1890 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
Romain Guy0147a172017-06-01 13:53:56 -07001891 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1892 );
1893}
1894
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001895// Returns a dataspace that fits all visible layers. The returned dataspace
1896// can only be one of
1897//
1898// - Dataspace::V0_SRGB
1899// - Dataspace::DISPLAY_P3
1900// - Dataspace::V0_SCRGB_LINEAR
1901// TODO(b/73825729) Add BT2020 data space.
1902ui::Dataspace SurfaceFlinger::getBestDataspace(
1903 const sp<const DisplayDevice>& displayDevice) const {
1904 Dataspace bestDataspace = Dataspace::V0_SRGB;
1905 for (const auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1906 switch (layer->getDataSpace()) {
1907 case Dataspace::V0_SCRGB:
1908 case Dataspace::V0_SCRGB_LINEAR:
1909 // return immediately
1910 return Dataspace::V0_SCRGB_LINEAR;
Peiyong Linf59a7192018-04-25 11:19:31 -07001911 case Dataspace::DISPLAY_P3:
1912 bestDataspace = Dataspace::DISPLAY_P3;
1913 break;
1914 // Historically, HDR dataspaces are ignored by SurfaceFlinger. But
1915 // since SurfaceFlinger simulates HDR support now, it should honor
1916 // them unless there is also native support.
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001917 case Dataspace::BT2020_PQ:
1918 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin62665892018-04-16 11:07:44 -07001919 if (!displayDevice->hasHDR10Support()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001920 return Dataspace::V0_SCRGB_LINEAR;
1921 }
1922 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001923 case Dataspace::BT2020_HLG:
1924 case Dataspace::BT2020_ITU_HLG:
1925 if (!displayDevice->hasHLGSupport()) {
1926 return Dataspace::V0_SCRGB_LINEAR;
1927 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001928 break;
1929 default:
1930 break;
1931 }
Romain Guy54f154a2017-10-24 21:40:32 +01001932 }
1933
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001934 return bestDataspace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001935}
1936
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001937// Pick the ColorMode / Dataspace for the display device.
1938// TODO(b/73825729) Add BT2020 color mode.
1939void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& displayDevice,
1940 ColorMode* outMode, Dataspace* outDataSpace) const {
1941 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1942 *outMode = ColorMode::NATIVE;
1943 *outDataSpace = Dataspace::UNKNOWN;
1944 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001945 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001946
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001947 switch (getBestDataspace(displayDevice)) {
1948 case Dataspace::DISPLAY_P3:
1949 case Dataspace::V0_SCRGB_LINEAR:
1950 *outMode = ColorMode::DISPLAY_P3;
1951 *outDataSpace = Dataspace::DISPLAY_P3;
1952 break;
1953 default:
1954 *outMode = ColorMode::SRGB;
1955 *outDataSpace = Dataspace::V0_SRGB;
1956 break;
1957 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001958}
1959
Mathias Agopiancd60f992012-08-16 16:28:27 -07001960void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001961 ATRACE_CALL();
1962 ALOGV("setUpHWComposer");
1963
Jesse Hall028dc8f2013-08-20 16:35:32 -07001964 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Dan Stozac7a25ad2018-04-12 11:45:09 -07001965 bool dirty = !mDisplays[dpy]->getDirtyRegion(mRepaintEverything).isEmpty();
Jesse Hallb7a05492014-08-14 15:45:06 -07001966 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1967 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1968
1969 // If nothing has changed (!dirty), don't recompose.
1970 // If something changed, but we don't currently have any visible layers,
1971 // and didn't when we last did a composition, then skip it this time.
1972 // The second rule does two things:
1973 // - When all layers are removed from a display, we'll emit one black
1974 // frame, then nothing more until we get new layers.
1975 // - When a display is created with a private layer stack, we won't
1976 // emit any black frames until a layer is added to the layer stack.
1977 bool mustRecompose = dirty && !(empty && wasEmpty);
1978
1979 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1980 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1981 mustRecompose ? "doing" : "skipping",
1982 dirty ? "+" : "-",
1983 empty ? "+" : "-",
1984 wasEmpty ? "+" : "-");
1985
Dan Stoza71433162014-02-04 16:22:36 -08001986 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001987
1988 if (mustRecompose) {
1989 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1990 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001991 }
1992
Dan Stoza9e56aa02015-11-02 13:00:03 -08001993 // build the h/w work list
1994 if (CC_UNLIKELY(mGeometryInvalid)) {
1995 mGeometryInvalid = false;
1996 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1997 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1998 const auto hwcId = displayDevice->getHwcDisplayId();
1999 if (hwcId >= 0) {
2000 const Vector<sp<Layer>>& currentLayers(
2001 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08002002 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002003 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08002004 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07002005 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002006 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002007 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07002008 }
2009 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07002010
Robert Carrae060832016-11-28 10:51:00 -08002011 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002012 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002013 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07002014 }
2015 }
2016 }
2017 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002018 }
Riley Andrews03414a12014-07-01 14:22:59 -07002019
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002020
Romain Guy0147a172017-06-01 13:53:56 -07002021 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002022
Dan Stoza9e56aa02015-11-02 13:00:03 -08002023 // Set the per-frame data
2024 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2025 auto& displayDevice = mDisplays[displayId];
2026 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002027
Dan Stoza9e56aa02015-11-02 13:00:03 -08002028 if (hwcId < 0) {
2029 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07002030 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002031 if (colorMatrix != mPreviousColorMatrix) {
Yiwei Zhang7c64f172018-03-07 14:52:28 -08002032 displayDevice->setColorTransform(colorMatrix);
David Sodman105b7dc2017-11-04 20:28:14 -07002033 status_t result = getBE().mHwc->setColorTransform(hwcId, colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002034 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
2035 "display %zd: %d", displayId, result);
2036 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002037 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002038 if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2039 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Peiyong Lin62665892018-04-16 11:07:44 -07002040 !displayDevice->hasHDR10Support()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002041 layer->forceClientComposition(hwcId);
2042 }
Peiyong Linf59a7192018-04-25 11:19:31 -07002043 if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
2044 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
2045 !displayDevice->hasHLGSupport()) {
2046 layer->forceClientComposition(hwcId);
2047 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002048
chaviwc9232ed2017-11-14 15:31:15 -08002049 if (layer->getForceClientComposition(hwcId)) {
2050 ALOGV("[%s] Requesting Client composition", layer->getName().string());
2051 layer->setCompositionType(hwcId, HWC2::Composition::Client);
2052 continue;
2053 }
2054
Dan Stoza9e56aa02015-11-02 13:00:03 -08002055 layer->setPerFrameData(displayDevice);
2056 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002057
2058 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002059 ColorMode colorMode;
2060 Dataspace dataSpace;
2061 pickColorMode(displayDevice, &colorMode, &dataSpace);
2062 setActiveColorModeInternal(displayDevice, colorMode, dataSpace);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002063 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002064 }
2065
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002066 mPreviousColorMatrix = colorMatrix;
2067
Dan Stoza9e56aa02015-11-02 13:00:03 -08002068 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002069 auto& displayDevice = mDisplays[displayId];
2070 if (!displayDevice->isDisplayOn()) {
2071 continue;
2072 }
2073
David Sodman105b7dc2017-11-04 20:28:14 -07002074 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002075 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2076 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002077 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002078}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002079
Mathias Agopiancd60f992012-08-16 16:28:27 -07002080void SurfaceFlinger::doComposition() {
2081 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002082 ALOGV("doComposition");
2083
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002084 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002085 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002086 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002087 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002088 // transform the dirty region into this screen's coordinate space
2089 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002090
2091 // repaint the framebuffer (if needed)
2092 doDisplayComposition(hw, dirtyRegion);
2093
Mathias Agopiancd60f992012-08-16 16:28:27 -07002094 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002095 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002096 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002097 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002098 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002099}
2100
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002101void SurfaceFlinger::postFramebuffer()
2102{
Mathias Agopian841cde52012-03-01 15:44:37 -08002103 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002104 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002105
Mathias Agopiana44b0412011-10-16 18:46:35 -07002106 const nsecs_t now = systemTime();
2107 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002108
Dan Stoza9e56aa02015-11-02 13:00:03 -08002109 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2110 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002111 if (!displayDevice->isDisplayOn()) {
2112 continue;
2113 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002114 const auto hwcId = displayDevice->getHwcDisplayId();
2115 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002116 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002117 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002118 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002119 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002120 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002121 // The layer buffer from the previous frame (if any) is released
2122 // by HWC only when the release fence from this frame (if any) is
2123 // signaled. Always get the release fence from HWC first.
2124 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002125 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002126
2127 // If the layer was client composited in the previous frame, we
2128 // need to merge with the previous client target acquire fence.
2129 // Since we do not track that, always merge with the current
2130 // client target acquire fence when it is available, even though
2131 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002132 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002133 releaseFence = Fence::merge("LayerRelease", releaseFence,
2134 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002135 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002136
Dan Stoza9e56aa02015-11-02 13:00:03 -08002137 layer->onLayerDisplayed(releaseFence);
2138 }
Chia-I Wu83806892017-11-16 10:50:20 -08002139
2140 // We've got a list of layers needing fences, that are disjoint with
2141 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2142 // supply them with the present fence.
2143 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002144 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002145 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2146 layer->onLayerDisplayed(presentFence);
2147 }
2148 }
2149
Dan Stoza9e56aa02015-11-02 13:00:03 -08002150 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002151 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002152 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002153 }
2154
Mathias Agopiana44b0412011-10-16 18:46:35 -07002155 mLastSwapBufferTime = systemTime() - now;
2156 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002157
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002158 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002159 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2160 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2161 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2162 logFrameStats();
2163 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002164 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002165}
2166
Mathias Agopian87baae12012-07-31 12:38:26 -07002167void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002168{
Mathias Agopian841cde52012-03-01 15:44:37 -08002169 ATRACE_CALL();
2170
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002171 // here we keep a copy of the drawing state (that is the state that's
2172 // going to be overwritten by handleTransactionLocked()) outside of
2173 // mStateLock so that the side-effects of the State assignment
2174 // don't happen with mStateLock held (which can cause deadlocks).
2175 State drawingState(mDrawingState);
2176
Mathias Agopianca4d3602011-05-19 15:38:14 -07002177 Mutex::Autolock _l(mStateLock);
2178 const nsecs_t now = systemTime();
2179 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002180
Mathias Agopianca4d3602011-05-19 15:38:14 -07002181 // Here we're guaranteed that some transaction flags are set
2182 // so we can call handleTransactionLocked() unconditionally.
2183 // We call getTransactionFlags(), which will also clear the flags,
2184 // with mStateLock held to guarantee that mCurrentState won't change
2185 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002186
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002187 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002188 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002189 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002190
Mathias Agopianca4d3602011-05-19 15:38:14 -07002191 mLastTransactionTime = systemTime() - now;
2192 mDebugInTransaction = 0;
2193 invalidateHwcGeometry();
2194 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002195}
2196
Lloyd Pique715a2c12017-12-14 17:18:08 -08002197DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique09594832018-01-22 17:48:03 -08002198 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002199 // Figure out whether the event is for the primary display or an
2200 // external display by matching the Hwc display id against one for a
2201 // connected display. If we did not find a match, we then check what
2202 // displays are not already connected to determine the type. If we don't
2203 // have a connected primary display, we assume the new display is meant to
2204 // be the primary display, and then if we don't have an external display,
2205 // we assume it is that.
2206 const auto primaryDisplayId =
2207 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2208 const auto externalDisplayId =
2209 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2210 if (primaryDisplayId && primaryDisplayId == display) {
2211 return DisplayDevice::DISPLAY_PRIMARY;
2212 } else if (externalDisplayId && externalDisplayId == display) {
2213 return DisplayDevice::DISPLAY_EXTERNAL;
2214 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2215 return DisplayDevice::DISPLAY_PRIMARY;
2216 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2217 return DisplayDevice::DISPLAY_EXTERNAL;
2218 }
2219
2220 return DisplayDevice::DISPLAY_ID_INVALID;
2221}
2222
Lloyd Piqueba04e622017-12-14 17:11:26 -08002223void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2224 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002225 auto displayType = determineDisplayType(event.display, event.connection);
2226 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2227 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2228 continue;
2229 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002230
2231 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2232 ALOGE("External displays are not supported by the vr hardware composer.");
2233 continue;
2234 }
2235
Lloyd Pique715a2c12017-12-14 17:18:08 -08002236 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002237
2238 if (event.connection == HWC2::Connection::Connected) {
Steven Thomas3bed0522018-03-20 15:40:48 -07002239 if (!mBuiltinDisplays[displayType].get()) {
2240 ALOGV("Creating built in display %d", displayType);
2241 mBuiltinDisplays[displayType] = new BBinder();
2242 // All non-virtual displays are currently considered secure.
2243 DisplayDeviceState info(displayType, true);
2244 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2245 "Built-in Screen" : "External Screen";
2246 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
Lloyd Pique4d234852018-01-22 17:21:36 -08002247 mInterceptor->saveDisplayCreation(info);
Steven Thomas3bed0522018-03-20 15:40:48 -07002248 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002249 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002250 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002251
Lloyd Piquefcd86612017-12-14 17:15:36 -08002252 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2253 if (idx >= 0) {
2254 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Lloyd Pique4d234852018-01-22 17:21:36 -08002255 mInterceptor->saveDisplayDeletion(info.displayId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002256 mCurrentState.displays.removeItemsAt(idx);
2257 }
2258 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002259 }
2260
2261 processDisplayChangesLocked();
2262 }
2263
2264 mPendingHotplugEvents.clear();
2265}
2266
Lloyd Pique09594832018-01-22 17:48:03 -08002267sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2268 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2269 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002270 bool hasWideColorGamut = false;
Lloyd Pique09594832018-01-22 17:48:03 -08002271 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002272 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Lloyd Pique09594832018-01-22 17:48:03 -08002273 for (ColorMode colorMode : modes) {
2274 switch (colorMode) {
2275 case ColorMode::DISPLAY_P3:
2276 case ColorMode::ADOBE_RGB:
2277 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002278 hasWideColorGamut = true;
Lloyd Pique09594832018-01-22 17:48:03 -08002279 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002280 // TODO(lpy) Handle BT2020, BT2100_PQ and BT2100_HLG properly.
Lloyd Pique09594832018-01-22 17:48:03 -08002281 default:
2282 break;
2283 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002284
2285 std::vector<RenderIntent> renderIntents = getHwComposer().getRenderIntents(hwcId,
2286 colorMode);
2287 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2288 for (auto intent : renderIntents) {
2289 if (intent == RenderIntent::ENHANCE) {
2290 mBuiltinDisplaySupportsEnhance = true;
2291 break;
2292 }
2293 }
2294 }
Lloyd Pique09594832018-01-22 17:48:03 -08002295 }
2296 }
2297
Peiyong Lin62665892018-04-16 11:07:44 -07002298 HdrCapabilities hdrCapabilities;
2299 getHwComposer().getHdrCapabilities(hwcId, &hdrCapabilities);
Lloyd Pique09594832018-01-22 17:48:03 -08002300
2301 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2302 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2303
2304 /*
2305 * Create our display's surface
2306 */
2307 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2308 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
2309 renderSurface->setAsync(state.type >= DisplayDevice::DISPLAY_VIRTUAL);
2310 renderSurface->setNativeWindow(nativeWindow.get());
2311 const int displayWidth = renderSurface->queryWidth();
2312 const int displayHeight = renderSurface->queryHeight();
2313
2314 // Make sure that composition can never be stalled by a virtual display
2315 // consumer that isn't processing buffers fast enough. We have to do this
2316 // in two places:
2317 // * Here, in case the display is composed entirely by HWC.
2318 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2319 // window's swap interval in eglMakeCurrent, so they'll override the
2320 // interval we set here.
2321 if (state.type >= DisplayDevice::DISPLAY_VIRTUAL) {
2322 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2323 }
2324
2325 // virtual displays are always considered enabled
2326 auto initialPowerMode = (state.type >= DisplayDevice::DISPLAY_VIRTUAL) ? HWC_POWER_MODE_NORMAL
2327 : HWC_POWER_MODE_OFF;
2328
2329 sp<DisplayDevice> hw =
2330 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2331 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
Peiyong Lin2c327ac2018-04-19 22:06:34 -07002332 hasWideColorGamut, hdrCapabilities,
2333 getHwComposer().getSupportedPerFrameMetadata(hwcId),
2334 initialPowerMode);
Lloyd Pique09594832018-01-22 17:48:03 -08002335
2336 if (maxFrameBufferAcquiredBuffers >= 3) {
2337 nativeWindowSurface->preallocateBuffers();
2338 }
2339
2340 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002341 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2342 if (hasWideColorGamut) {
Lloyd Pique09594832018-01-22 17:48:03 -08002343 defaultColorMode = ColorMode::SRGB;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002344 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique09594832018-01-22 17:48:03 -08002345 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002346 setActiveColorModeInternal(hw, defaultColorMode, defaultDataSpace);
Lloyd Pique09594832018-01-22 17:48:03 -08002347 hw->setLayerStack(state.layerStack);
2348 hw->setProjection(state.orientation, state.viewport, state.frame);
2349 hw->setDisplayName(state.displayName);
2350
2351 return hw;
2352}
2353
Lloyd Pique347200f2017-12-14 17:00:15 -08002354void SurfaceFlinger::processDisplayChangesLocked() {
2355 // here we take advantage of Vector's copy-on-write semantics to
2356 // improve performance by skipping the transaction entirely when
2357 // know that the lists are identical
2358 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2359 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2360 if (!curr.isIdenticalTo(draw)) {
2361 mVisibleRegionsDirty = true;
2362 const size_t cc = curr.size();
2363 size_t dc = draw.size();
2364
2365 // find the displays that were removed
2366 // (ie: in drawing state but not in current state)
2367 // also handle displays that changed
2368 // (ie: displays that are in both lists)
2369 for (size_t i = 0; i < dc;) {
2370 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2371 if (j < 0) {
2372 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002373 // Call makeCurrent() on the primary display so we can
2374 // be sure that nothing associated with this display
2375 // is current.
2376 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2377 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2378 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2379 if (hw != nullptr) hw->disconnect(getHwComposer());
2380 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2381 mEventThread->onHotplugReceived(draw[i].type, false);
2382 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002383 } else {
2384 // this display is in both lists. see if something changed.
2385 const DisplayDeviceState& state(curr[j]);
2386 const wp<IBinder>& display(curr.keyAt(j));
2387 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2388 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2389 if (state_binder != draw_binder) {
2390 // changing the surface is like destroying and
2391 // recreating the DisplayDevice, so we just remove it
2392 // from the drawing state, so that it get re-added
2393 // below.
2394 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2395 if (hw != nullptr) hw->disconnect(getHwComposer());
2396 mDisplays.removeItem(display);
2397 mDrawingState.displays.removeItemsAt(i);
2398 dc--;
2399 // at this point we must loop to the next item
2400 continue;
2401 }
2402
2403 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2404 if (disp != nullptr) {
2405 if (state.layerStack != draw[i].layerStack) {
2406 disp->setLayerStack(state.layerStack);
2407 }
2408 if ((state.orientation != draw[i].orientation) ||
2409 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2410 disp->setProjection(state.orientation, state.viewport, state.frame);
2411 }
2412 if (state.width != draw[i].width || state.height != draw[i].height) {
2413 disp->setDisplaySize(state.width, state.height);
2414 }
2415 }
2416 }
2417 ++i;
2418 }
2419
2420 // find displays that were added
2421 // (ie: in current state but not in drawing state)
2422 for (size_t i = 0; i < cc; i++) {
2423 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2424 const DisplayDeviceState& state(curr[i]);
2425
2426 sp<DisplaySurface> dispSurface;
2427 sp<IGraphicBufferProducer> producer;
2428 sp<IGraphicBufferProducer> bqProducer;
2429 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002430 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002431
2432 int32_t hwcId = -1;
2433 if (state.isVirtualDisplay()) {
2434 // Virtual displays without a surface are dormant:
2435 // they have external state (layer stack, projection,
2436 // etc.) but no internal state (i.e. a DisplayDevice).
2437 if (state.surface != nullptr) {
2438 // Allow VR composer to use virtual displays.
2439 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2440 int width = 0;
2441 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2442 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2443 int height = 0;
2444 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2445 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2446 int intFormat = 0;
2447 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2448 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002449 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002450
2451 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2452 }
2453
2454 // TODO: Plumb requested format back up to consumer
2455
2456 sp<VirtualDisplaySurface> vds =
2457 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2458 bqProducer, bqConsumer,
2459 state.displayName);
2460
2461 dispSurface = vds;
2462 producer = vds;
2463 }
2464 } else {
2465 ALOGE_IF(state.surface != nullptr,
2466 "adding a supported display, but rendering "
2467 "surface is provided (%p), ignoring it",
2468 state.surface.get());
2469
2470 hwcId = state.type;
2471 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2472 producer = bqProducer;
2473 }
2474
2475 const wp<IBinder>& display(curr.keyAt(i));
2476 if (dispSurface != nullptr) {
Lloyd Pique09594832018-01-22 17:48:03 -08002477 mDisplays.add(display,
2478 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2479 producer));
Lloyd Pique347200f2017-12-14 17:00:15 -08002480 if (!state.isVirtualDisplay()) {
2481 mEventThread->onHotplugReceived(state.type, true);
2482 }
2483 }
2484 }
2485 }
2486 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002487
2488 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002489}
2490
Mathias Agopian87baae12012-07-31 12:38:26 -07002491void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002492{
Dan Stoza7dde5992015-05-22 09:51:44 -07002493 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002494 mCurrentState.traverseInZOrder([](Layer* layer) {
2495 layer->notifyAvailableFrames();
2496 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002497
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002498 /*
2499 * Traversal of the children
2500 * (perform the transaction for each of them if needed)
2501 */
2502
Mathias Agopian3559b072012-08-15 13:46:03 -07002503 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002504 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002505 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002506 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002507
2508 const uint32_t flags = layer->doTransaction(0);
2509 if (flags & Layer::eVisibleRegion)
2510 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002511 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002512 }
2513
2514 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002515 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002516 */
2517
Mathias Agopiane57f2922012-08-09 16:29:12 -07002518 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002519 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002520 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002521 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002522
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002523 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002524 // The transform hint might have changed for some layers
2525 // (either because a display has changed, or because a layer
2526 // as changed).
2527 //
2528 // Walk through all the layers in currentLayers,
2529 // and update their transform hint.
2530 //
2531 // If a layer is visible only on a single display, then that
2532 // display is used to calculate the hint, otherwise we use the
2533 // default display.
2534 //
2535 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2536 // the hint is set before we acquire a buffer from the surface texture.
2537 //
2538 // NOTE: layer transactions have taken place already, so we use their
2539 // drawing state. However, SurfaceFlinger's own transaction has not
2540 // happened yet, so we must use the current state layer list
2541 // (soon to become the drawing state list).
2542 //
2543 sp<const DisplayDevice> disp;
2544 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002545 bool first = true;
2546 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002547 // NOTE: we rely on the fact that layers are sorted by
2548 // layerStack first (so we don't have to traverse the list
2549 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002550 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002551 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002552 currentlayerStack = layerStack;
2553 // figure out if this layerstack is mirrored
2554 // (more than one display) if so, pick the default display,
2555 // if not, pick the only display it's on.
2556 disp.clear();
2557 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2558 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002559 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002560 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002561 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002562 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002563 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002564 break;
2565 }
2566 }
2567 }
2568 }
Chet Haase91d25932013-04-11 15:24:55 -07002569
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002570 if (disp == nullptr) {
2571 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2572 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002573
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002574 // could be null when this layer is using a layerStack
2575 // that is not visible on any display. Also can occur at
2576 // screen off/on times.
2577 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002578 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002579
2580 // disp can be null if there is no display available at all to get
2581 // the transform hint from.
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002582 if (disp != nullptr) {
2583 layer->updateTransformHint(disp);
2584 }
Robert Carr2047fae2016-11-28 14:09:09 -08002585
2586 first = false;
2587 });
Mathias Agopian84300952012-11-21 16:02:13 -08002588 }
2589
2590
Mathias Agopian3559b072012-08-15 13:46:03 -07002591 /*
2592 * Perform our own transaction if needed
2593 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002594
2595 if (mLayersAdded) {
2596 mLayersAdded = false;
2597 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002598 mVisibleRegionsDirty = true;
2599 }
2600
2601 // some layers might have been removed, so
2602 // we need to update the regions they're exposing.
2603 if (mLayersRemoved) {
2604 mLayersRemoved = false;
2605 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002606 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002607 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002608 // this layer is not visible anymore
2609 // TODO: we could traverse the tree from front to back and
2610 // compute the actual visible region
2611 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002612 Region visibleReg;
2613 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002614 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002615 }
Robert Carr2047fae2016-11-28 14:09:09 -08002616 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002617 }
2618
2619 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002620
2621 updateCursorAsync();
2622}
2623
2624void SurfaceFlinger::updateCursorAsync()
2625{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002626 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2627 auto& displayDevice = mDisplays[displayId];
2628 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002629 continue;
2630 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002631
2632 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2633 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002634 }
2635 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002636}
2637
2638void SurfaceFlinger::commitTransaction()
2639{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002640 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002641 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002642 for (const auto& l : mLayersPendingRemoval) {
2643 recordBufferingStats(l->getName().string(),
2644 l->getOccupancyHistory(true));
2645 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002646 }
2647 mLayersPendingRemoval.clear();
2648 }
2649
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002650 // If this transaction is part of a window animation then the next frame
2651 // we composite should be considered an animation as well.
2652 mAnimCompositionPending = mAnimTransactionPending;
2653
Mathias Agopian4fec8732012-06-29 14:12:52 -07002654 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002655 mDrawingState.traverseInZOrder([](Layer* layer) {
2656 layer->commitChildList();
2657 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002658 mTransactionPending = false;
2659 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002660 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002661}
2662
Chia-I Wuab0c3192017-08-01 11:29:00 -07002663void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002664 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002665{
Mathias Agopian841cde52012-03-01 15:44:37 -08002666 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002667 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002668
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002669 Region aboveOpaqueLayers;
2670 Region aboveCoveredLayers;
2671 Region dirty;
2672
Mathias Agopian87baae12012-07-31 12:38:26 -07002673 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002674
Robert Carr2047fae2016-11-28 14:09:09 -08002675 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002676 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002677 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002678
Jesse Hall01e29052013-02-19 16:13:35 -08002679 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002680 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002681 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002682
Mathias Agopianab028732010-03-16 16:41:46 -07002683 /*
2684 * opaqueRegion: area of a surface that is fully opaque.
2685 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002686 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002687
2688 /*
2689 * visibleRegion: area of a surface that is visible on screen
2690 * and not fully transparent. This is essentially the layer's
2691 * footprint minus the opaque regions above it.
2692 * Areas covered by a translucent surface are considered visible.
2693 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002694 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002695
2696 /*
2697 * coveredRegion: area of a surface that is covered by all
2698 * visible regions above it (which includes the translucent areas).
2699 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002700 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002701
Jesse Halla8026d22012-09-25 13:25:04 -07002702 /*
2703 * transparentRegion: area of a surface that is hinted to be completely
2704 * transparent. This is only used to tell when the layer has no visible
2705 * non-transparent regions and can be removed from the layer list. It
2706 * does not affect the visibleRegion of this layer or any layers
2707 * beneath it. The hint may not be correct if apps don't respect the
2708 * SurfaceView restrictions (which, sadly, some don't).
2709 */
2710 Region transparentRegion;
2711
Mathias Agopianab028732010-03-16 16:41:46 -07002712
2713 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002714 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002715 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002716 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002717 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002718 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002719 if (!visibleRegion.isEmpty()) {
2720 // Remove the transparent area from the visible region
2721 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002722 if (tr.preserveRects()) {
2723 // transform the transparent region
2724 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002725 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002726 // transformation too complex, can't do the
2727 // transparent region optimization.
2728 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002729 }
Mathias Agopianab028732010-03-16 16:41:46 -07002730 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002731
Mathias Agopianab028732010-03-16 16:41:46 -07002732 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002733 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002734 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002735 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2736 // the opaque region is the layer's footprint
2737 opaqueRegion = visibleRegion;
2738 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002739 }
2740 }
2741
Robert Carre5f4f692018-01-12 13:12:28 -08002742 if (visibleRegion.isEmpty()) {
2743 layer->clearVisibilityRegions();
2744 return;
2745 }
2746
Mathias Agopianab028732010-03-16 16:41:46 -07002747 // Clip the covered region to the visible region
2748 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2749
2750 // Update aboveCoveredLayers for next (lower) layer
2751 aboveCoveredLayers.orSelf(visibleRegion);
2752
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002753 // subtract the opaque region covered by the layers above us
2754 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002755
2756 // compute this layer's dirty region
2757 if (layer->contentDirty) {
2758 // we need to invalidate the whole region
2759 dirty = visibleRegion;
2760 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002761 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002762 layer->contentDirty = false;
2763 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002764 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002765 * the exposed region consists of two components:
2766 * 1) what's VISIBLE now and was COVERED before
2767 * 2) what's EXPOSED now less what was EXPOSED before
2768 *
2769 * note that (1) is conservative, we start with the whole
2770 * visible region but only keep what used to be covered by
2771 * something -- which mean it may have been exposed.
2772 *
2773 * (2) handles areas that were not covered by anything but got
2774 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002775 */
Mathias Agopianab028732010-03-16 16:41:46 -07002776 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002777 const Region oldVisibleRegion = layer->visibleRegion;
2778 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002779 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2780 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002781 }
2782 dirty.subtractSelf(aboveOpaqueLayers);
2783
2784 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002785 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002786
Mathias Agopianab028732010-03-16 16:41:46 -07002787 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002788 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002789
Jesse Halla8026d22012-09-25 13:25:04 -07002790 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002791 layer->setVisibleRegion(visibleRegion);
2792 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002793 layer->setVisibleNonTransparentRegion(
2794 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002795 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002796
Mathias Agopian87baae12012-07-31 12:38:26 -07002797 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002798}
2799
Chia-I Wuab0c3192017-08-01 11:29:00 -07002800void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002801 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002802 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002803 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002804 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002805 }
2806 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002807}
2808
Dan Stoza6b9454d2014-11-07 16:00:59 -08002809bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002810{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002811 ALOGV("handlePageFlip");
2812
Brian Andersond6927fb2016-07-23 23:37:30 -07002813 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002814
Mathias Agopian4fec8732012-06-29 14:12:52 -07002815 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002816 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002817 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002818
2819 // Store the set of layers that need updates. This set must not change as
2820 // buffers are being latched, as this could result in a deadlock.
2821 // Example: Two producers share the same command stream and:
2822 // 1.) Layer 0 is latched
2823 // 2.) Layer 0 gets a new frame
2824 // 2.) Layer 1 gets a new frame
2825 // 3.) Layer 1 is latched.
2826 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2827 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002828 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002829 if (layer->hasQueuedFrame()) {
2830 frameQueued = true;
2831 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002832 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002833 } else {
2834 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002835 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002836 } else {
2837 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002838 }
Robert Carr2047fae2016-11-28 14:09:09 -08002839 });
2840
Dan Stoza9e56aa02015-11-02 13:00:03 -08002841 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002842 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002843 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002844 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002845 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002846 newDataLatched = true;
2847 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002848 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002849
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002850 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002851
2852 // If we will need to wake up at some time in the future to deal with a
2853 // queued frame that shouldn't be displayed during this vsync period, wake
2854 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002855 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002856 signalLayerUpdate();
2857 }
2858
2859 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002860 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002861}
2862
Mathias Agopianad456f92011-01-13 17:53:01 -08002863void SurfaceFlinger::invalidateHwcGeometry()
2864{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002865 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002866}
2867
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002868
Fabien Sanglard830b8472016-11-30 16:35:58 -08002869void SurfaceFlinger::doDisplayComposition(
2870 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002871 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002872{
Dan Stoza71433162014-02-04 16:22:36 -08002873 // We only need to actually compose the display if:
2874 // 1) It is being handled by hardware composer, which may need this to
2875 // keep its virtual display state machine in sync, or
2876 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002877 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002878 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002879 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002880 return;
2881 }
2882
Dan Stoza9e56aa02015-11-02 13:00:03 -08002883 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002884 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002885
2886 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002887 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002888}
2889
Chia-I Wub02087d2017-11-09 10:19:54 -08002890bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002891{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002892 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002893
Chia-I Wub02087d2017-11-09 10:19:54 -08002894 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002895 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002896 const auto hwcId = displayDevice->getHwcDisplayId();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002897 const bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
2898 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
2899 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2900 HWC2::Capability::SkipClientColorTransform);
2901 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002902
2903 mat4 oldColorMatrix;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002904 mat4 legacySrgbSaturationMatrix = mLegacySrgbSaturationMatrix;
2905 const bool applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002906 if (applyColorMatrix) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002907 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002908 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002909 legacySrgbSaturationMatrix = colorMatrix * legacySrgbSaturationMatrix;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002910 }
2911
Dan Stoza9e56aa02015-11-02 13:00:03 -08002912 if (hasClientComposition) {
2913 ALOGV("hasClientComposition");
2914
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002915 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002916 if (displayDevice->hasWideColorGamut()) {
2917 outputDataspace = displayDevice->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002918 }
2919 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
2920
Chia-I Wu7f402902017-11-09 12:51:10 -08002921 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002922 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002923 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002924 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002925
2926 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002927 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002928 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2929 }
2930 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002931 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002932
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002933 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002934 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002935 // when using overlays, we assume a fully transparent framebuffer
2936 // NOTE: we could reduce how much we need to clear, for instance
2937 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002938 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002939 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002940 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002941 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002942 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002943 // we're left with the letterbox region
2944 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002945 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002946
2947 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002948 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002949
Mathias Agopianb9494d52012-04-18 02:28:45 -07002950 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002951 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002952 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002953 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002954 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002955 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002956
Dan Stoza9e56aa02015-11-02 13:00:03 -08002957 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002958 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002959 // scissor on the main display. It should never be needed
2960 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002961 const Rect& bounds(displayDevice->getBounds());
2962 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002963 if (scissor != bounds) {
2964 // scissor doesn't match the screen's dimensions, so we
2965 // need to clear everything outside of it and enable
2966 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002967
Mathias Agopianf45c5102012-10-24 16:29:17 -07002968 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002969 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002970 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002971 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002972 }
2973 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002974 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002975
Mathias Agopian85d751c2012-08-29 16:59:24 -07002976 /*
2977 * and then, render the layers targeted at the framebuffer
2978 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002979
Dan Stoza9e56aa02015-11-02 13:00:03 -08002980 ALOGV("Rendering client layers");
2981 const Transform& displayTransform = displayDevice->getTransform();
2982 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002983 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002984 bool firstLayer = true;
2985 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002986 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002987 displayTransform.transform(layer->visibleRegion)));
2988 ALOGV("Layer: %s", layer->getName().string());
2989 ALOGV(" Composition type: %s",
2990 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002991 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002992 switch (layer->getCompositionType(hwcId)) {
2993 case HWC2::Composition::Cursor:
2994 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002995 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002996 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002997 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002998 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002999 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08003000 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07003001 // never clear the very first layer since we're
3002 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07003003 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003004 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003005 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003006 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003007 case HWC2::Composition::Client: {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003008 // Only apply saturation matrix layer that is legacy SRGB dataspace
3009 // when auto color mode is on.
3010 bool restore = false;
3011 mat4 savedMatrix;
3012 if (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
3013 layer->isLegacySrgbDataSpace()) {
3014 savedMatrix =
3015 getRenderEngine().setupColorTransform(legacySrgbSaturationMatrix);
3016 restore = true;
3017 }
chaviwa76b2712017-09-20 12:02:26 -07003018 layer->draw(renderArea, clip);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003019 if (restore) {
3020 getRenderEngine().setupColorTransform(savedMatrix);
3021 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003022 break;
3023 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003024 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07003025 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003026 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003027 } else {
3028 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003029 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003030 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003031 }
3032 } else {
3033 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08003034 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08003035 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08003036 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07003037 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07003038 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07003039 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003040 }
3041 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003042
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003043 if (applyColorMatrix) {
3044 getRenderEngine().setupColorTransform(oldColorMatrix);
3045 }
3046
Mathias Agopianf45c5102012-10-24 16:29:17 -07003047 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003048 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003049 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003050}
3051
Fabien Sanglard830b8472016-11-30 16:35:58 -08003052void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
3053 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003054 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003055 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003056}
3057
Dan Stoza7d89d062015-04-30 13:29:25 -07003058status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003059 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003060 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003061 const sp<Layer>& lbc,
3062 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003063{
Dan Stoza7d89d062015-04-30 13:29:25 -07003064 // add this layer to the current state list
3065 {
3066 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003067 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003068 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3069 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003070 return NO_MEMORY;
3071 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003072 if (parent == nullptr) {
3073 mCurrentState.layersSortedByZ.add(lbc);
3074 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003075 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003076 ALOGE("addClientLayer called with a removed parent");
3077 return NAME_NOT_FOUND;
3078 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003079 parent->addChild(lbc);
3080 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003081
Dan Stoza101d8dc2018-02-27 15:42:25 -08003082 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
Dan Stoza0a0158c2018-03-16 13:38:54 -07003083 // TODO (b/74616334): Change this back to a fatal assert once the leak is fixed
3084 ALOGE_IF(mGraphicBufferProducerList.size() > mMaxGraphicBufferProducerListSize,
3085 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3086 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize,
3087 mNumLayers);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003088 mLayersAdded = true;
3089 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003090 }
3091
Mathias Agopian96f08192010-06-02 23:28:45 -07003092 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003093 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003094
Dan Stoza7d89d062015-04-30 13:29:25 -07003095 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003096}
3097
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003098status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003099 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003100 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3101}
Robert Carr7f9b8992017-03-10 11:08:39 -08003102
chaviwca27f252018-02-06 16:46:39 -08003103status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3104 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003105 if (layer->isPendingRemoval()) {
3106 return NO_ERROR;
3107 }
3108
Robert Carr1f0a16a2016-10-24 16:27:39 -07003109 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003110 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003111 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003112 if (topLevelOnly) {
3113 return NO_ERROR;
3114 }
3115
Chia-I Wu98f1c102017-05-30 14:54:08 -07003116 sp<Layer> ancestor = p;
3117 while (ancestor->getParent() != nullptr) {
3118 ancestor = ancestor->getParent();
3119 }
3120 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3121 ALOGE("removeLayer called with a layer whose parent has been removed");
3122 return NAME_NOT_FOUND;
3123 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003124
3125 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003126 } else {
3127 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003128 }
3129
Robert Carr136e2f62017-02-08 17:54:29 -08003130 // As a matter of normal operation, the LayerCleaner will produce a second
3131 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3132 // so we will succeed in promoting it, but it's already been removed
3133 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3134 // otherwise something has gone wrong and we are leaking the layer.
3135 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003136 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3137 layer->getName().string(),
3138 (p != nullptr) ? p->getName().string() : "no-parent");
3139 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003140 } else if (index < 0) {
3141 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003142 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003143
Chia-I Wuc6657022017-08-15 11:18:17 -07003144 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003145 mLayersPendingRemoval.add(layer);
3146 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003147 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003148 setTransactionFlags(eTransactionNeeded);
3149 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003150}
3151
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003152uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003153 return android_atomic_release_load(&mTransactionFlags);
3154}
3155
Mathias Agopian3f844832013-08-07 21:24:32 -07003156uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003157 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3158}
3159
Mathias Agopian3f844832013-08-07 21:24:32 -07003160uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza2713c302018-03-28 17:07:36 -07003161 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3162}
3163
3164uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3165 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003166 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza2713c302018-03-28 17:07:36 -07003167 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003168 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003169 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003170 }
3171 return old;
3172}
3173
chaviwca27f252018-02-06 16:46:39 -08003174bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3175 for (const ComposerState& state : states) {
3176 // Here we need to check that the interface we're given is indeed
3177 // one of our own. A malicious client could give us a nullptr
3178 // IInterface, or one of its own or even one of our own but a
3179 // different type. All these situations would cause us to crash.
3180 if (state.client == nullptr) {
3181 return true;
3182 }
3183
3184 sp<IBinder> binder = IInterface::asBinder(state.client);
3185 if (binder == nullptr) {
3186 return true;
3187 }
3188
3189 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3190 return true;
3191 }
3192 }
3193 return false;
3194}
3195
Mathias Agopian8b33f032012-07-24 20:43:54 -07003196void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003197 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003198 const Vector<DisplayState>& displays,
3199 uint32_t flags)
3200{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003201 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003202 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003203 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003204
chaviwca27f252018-02-06 16:46:39 -08003205 if (containsAnyInvalidClientState(states)) {
3206 return;
3207 }
3208
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003209 if (flags & eAnimation) {
3210 // For window updates that are part of an animation we must wait for
3211 // previous animation "frames" to be handled.
3212 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003213 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003214 if (CC_UNLIKELY(err != NO_ERROR)) {
3215 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003216 // caller after a few seconds.
3217 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3218 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003219 mAnimTransactionPending = false;
3220 break;
3221 }
3222 }
3223 }
3224
chaviwca27f252018-02-06 16:46:39 -08003225 for (const DisplayState& display : displays) {
3226 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003227 }
3228
chaviwca27f252018-02-06 16:46:39 -08003229 for (const ComposerState& state : states) {
3230 transactionFlags |= setClientStateLocked(state);
3231 }
3232
3233 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3234 // as destroyed should only occur after setting all other states. This is to allow for a
3235 // child re-parent to happen before marking its original parent as destroyed (which would
3236 // then mark the child as destroyed).
3237 for (const ComposerState& state : states) {
3238 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003239 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003240
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003241 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3242 // anyway. This can be used as a flush mechanism for previous async transactions.
3243 // Empty animation transaction can be used to simulate back-pressure, so also force a
3244 // transaction for empty animation transactions.
3245 if (transactionFlags == 0 &&
3246 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003247 transactionFlags = eTransactionNeeded;
3248 }
3249
Mathias Agopian386aa982011-11-07 21:58:03 -08003250 if (transactionFlags) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003251 if (mInterceptor->isEnabled()) {
3252 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003253 }
Irvel468051e2016-06-13 16:44:44 -07003254
Mathias Agopian386aa982011-11-07 21:58:03 -08003255 // this triggers the transaction
Dan Stoza2713c302018-03-28 17:07:36 -07003256 const auto start = (flags & eEarlyWakeup)
3257 ? VSyncModulator::TransactionStart::EARLY
3258 : VSyncModulator::TransactionStart::NORMAL;
3259 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003260
3261 // if this is a synchronous transaction, wait for it to take effect
3262 // before returning.
3263 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003264 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003265 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003266 if (flags & eAnimation) {
3267 mAnimTransactionPending = true;
3268 }
3269 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003270 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3271 if (CC_UNLIKELY(err != NO_ERROR)) {
3272 // just in case something goes wrong in SF, return to the
3273 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003274 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3275 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003276 break;
3277 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003278 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003279 }
3280}
3281
Mathias Agopiane57f2922012-08-09 16:29:12 -07003282uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3283{
Jesse Hall9a143922012-10-04 16:29:19 -07003284 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3285 if (dpyIdx < 0)
3286 return 0;
3287
Mathias Agopiane57f2922012-08-09 16:29:12 -07003288 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003289 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003290 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003291 const uint32_t what = s.what;
3292 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003293 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003294 disp.surface = s.surface;
3295 flags |= eDisplayTransactionNeeded;
3296 }
3297 }
3298 if (what & DisplayState::eLayerStackChanged) {
3299 if (disp.layerStack != s.layerStack) {
3300 disp.layerStack = s.layerStack;
3301 flags |= eDisplayTransactionNeeded;
3302 }
3303 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003304 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003305 if (disp.orientation != s.orientation) {
3306 disp.orientation = s.orientation;
3307 flags |= eDisplayTransactionNeeded;
3308 }
3309 if (disp.frame != s.frame) {
3310 disp.frame = s.frame;
3311 flags |= eDisplayTransactionNeeded;
3312 }
3313 if (disp.viewport != s.viewport) {
3314 disp.viewport = s.viewport;
3315 flags |= eDisplayTransactionNeeded;
3316 }
3317 }
Michael Lentine47e45402014-07-18 15:34:25 -07003318 if (what & DisplayState::eDisplaySizeChanged) {
3319 if (disp.width != s.width) {
3320 disp.width = s.width;
3321 flags |= eDisplayTransactionNeeded;
3322 }
3323 if (disp.height != s.height) {
3324 disp.height = s.height;
3325 flags |= eDisplayTransactionNeeded;
3326 }
3327 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003328 }
3329 return flags;
3330}
3331
chaviwca27f252018-02-06 16:46:39 -08003332uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3333 const layer_state_t& s = composerState.state;
3334 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3335
Mathias Agopian13127d82013-03-05 17:47:11 -08003336 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003337 if (layer == nullptr) {
3338 return 0;
3339 }
3340
3341 if (layer->isPendingRemoval()) {
3342 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3343 return 0;
3344 }
3345
3346 uint32_t flags = 0;
3347
3348 const uint32_t what = s.what;
3349 bool geometryAppliesWithResize =
3350 what & layer_state_t::eGeometryAppliesWithResize;
3351 if (what & layer_state_t::ePositionChanged) {
3352 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3353 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003354 }
chaviw8b3871a2017-11-01 17:41:01 -07003355 }
3356 if (what & layer_state_t::eLayerChanged) {
3357 // NOTE: index needs to be calculated before we update the state
3358 const auto& p = layer->getParent();
3359 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003360 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003361 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003362 mCurrentState.layersSortedByZ.removeAt(idx);
3363 mCurrentState.layersSortedByZ.add(layer);
3364 // we need traversal (state changed)
3365 // AND transaction (list changed)
3366 flags |= eTransactionNeeded|eTraversalNeeded;
3367 }
chaviw8b3871a2017-11-01 17:41:01 -07003368 } else {
3369 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003370 flags |= eTransactionNeeded|eTraversalNeeded;
3371 }
3372 }
chaviw8b3871a2017-11-01 17:41:01 -07003373 }
3374 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003375 // NOTE: index needs to be calculated before we update the state
3376 const auto& p = layer->getParent();
3377 if (p == nullptr) {
3378 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3379 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3380 mCurrentState.layersSortedByZ.removeAt(idx);
3381 mCurrentState.layersSortedByZ.add(layer);
3382 // we need traversal (state changed)
3383 // AND transaction (list changed)
3384 flags |= eTransactionNeeded|eTraversalNeeded;
3385 }
3386 } else {
3387 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3388 flags |= eTransactionNeeded|eTraversalNeeded;
3389 }
chaviw8b3871a2017-11-01 17:41:01 -07003390 }
3391 }
3392 if (what & layer_state_t::eSizeChanged) {
3393 if (layer->setSize(s.w, s.h)) {
3394 flags |= eTraversalNeeded;
3395 }
3396 }
3397 if (what & layer_state_t::eAlphaChanged) {
3398 if (layer->setAlpha(s.alpha))
3399 flags |= eTraversalNeeded;
3400 }
3401 if (what & layer_state_t::eColorChanged) {
3402 if (layer->setColor(s.color))
3403 flags |= eTraversalNeeded;
3404 }
3405 if (what & layer_state_t::eMatrixChanged) {
3406 if (layer->setMatrix(s.matrix))
3407 flags |= eTraversalNeeded;
3408 }
3409 if (what & layer_state_t::eTransparentRegionChanged) {
3410 if (layer->setTransparentRegionHint(s.transparentRegion))
3411 flags |= eTraversalNeeded;
3412 }
3413 if (what & layer_state_t::eFlagsChanged) {
3414 if (layer->setFlags(s.flags, s.mask))
3415 flags |= eTraversalNeeded;
3416 }
3417 if (what & layer_state_t::eCropChanged) {
3418 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3419 flags |= eTraversalNeeded;
3420 }
3421 if (what & layer_state_t::eFinalCropChanged) {
3422 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3423 flags |= eTraversalNeeded;
3424 }
3425 if (what & layer_state_t::eLayerStackChanged) {
3426 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3427 // We only allow setting layer stacks for top level layers,
3428 // everything else inherits layer stack from its parent.
3429 if (layer->hasParent()) {
3430 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3431 layer->getName().string());
3432 } else if (idx < 0) {
3433 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3434 "that also does not appear in the top level layer list. Something"
3435 " has gone wrong.", layer->getName().string());
3436 } else if (layer->setLayerStack(s.layerStack)) {
3437 mCurrentState.layersSortedByZ.removeAt(idx);
3438 mCurrentState.layersSortedByZ.add(layer);
3439 // we need traversal (state changed)
3440 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003441 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003442 }
3443 }
3444 if (what & layer_state_t::eDeferTransaction) {
3445 if (s.barrierHandle != nullptr) {
3446 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3447 } else if (s.barrierGbp != nullptr) {
3448 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3449 if (authenticateSurfaceTextureLocked(gbp)) {
3450 const auto& otherLayer =
3451 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3452 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3453 } else {
3454 ALOGE("Attempt to defer transaction to to an"
3455 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003456 }
3457 }
chaviw8b3871a2017-11-01 17:41:01 -07003458 // We don't trigger a traversal here because if no other state is
3459 // changed, we don't want this to cause any more work
3460 }
3461 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003462 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003463 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003464 if (!hadParent) {
3465 mCurrentState.layersSortedByZ.remove(layer);
3466 }
chaviw8b3871a2017-11-01 17:41:01 -07003467 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003468 }
chaviw8b3871a2017-11-01 17:41:01 -07003469 }
3470 if (what & layer_state_t::eReparentChildren) {
3471 if (layer->reparentChildren(s.reparentHandle)) {
3472 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003473 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003474 }
chaviw8b3871a2017-11-01 17:41:01 -07003475 if (what & layer_state_t::eDetachChildren) {
3476 layer->detachChildren();
3477 }
3478 if (what & layer_state_t::eOverrideScalingModeChanged) {
3479 layer->setOverrideScalingMode(s.overrideScalingMode);
3480 // We don't trigger a traversal here because if no other state is
3481 // changed, we don't want this to cause any more work
3482 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003483 return flags;
3484}
3485
chaviwca27f252018-02-06 16:46:39 -08003486void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3487 const layer_state_t& state = composerState.state;
3488 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3489
3490 sp<Layer> layer(client->getLayerUser(state.surface));
3491 if (layer == nullptr) {
3492 return;
3493 }
3494
3495 if (layer->isPendingRemoval()) {
3496 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3497 return;
3498 }
3499
3500 if (state.what & layer_state_t::eDestroySurface) {
3501 removeLayerLocked(mStateLock, layer);
3502 }
3503}
3504
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003505status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003506 const String8& name,
3507 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003508 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliuccd34842018-03-14 12:26:23 -07003509 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003510 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003511{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003512 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003513 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003514 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003515 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003516 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003517
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003518 status_t result = NO_ERROR;
3519
3520 sp<Layer> layer;
3521
Cody Northropbc755282017-03-31 12:00:08 -06003522 String8 uniqueName = getUniqueLayerName(name);
3523
Mathias Agopian3165cc22012-08-08 19:42:09 -07003524 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3525 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003526 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003527 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003528 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003529
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003530 break;
chaviw13fdc492017-06-27 12:40:18 -07003531 case ISurfaceComposerClient::eFXSurfaceColor:
3532 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003533 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003534 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003535 break;
3536 default:
3537 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003538 break;
3539 }
3540
Dan Stoza7d89d062015-04-30 13:29:25 -07003541 if (result != NO_ERROR) {
3542 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003543 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003544
Chia-I Wuab0c3192017-08-01 11:29:00 -07003545 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3546 // TODO b/64227542
3547 if (windowType == 441731) {
3548 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3549 layer->setPrimaryDisplayOnly();
3550 }
3551
Albert Chaulk479c60c2017-01-27 14:21:34 -05003552 layer->setInfo(windowType, ownerUid);
3553
Robert Carr1f0a16a2016-10-24 16:27:39 -07003554 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003555 if (result != NO_ERROR) {
3556 return result;
3557 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003558 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003559
3560 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003561 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003562}
3563
Cody Northropbc755282017-03-31 12:00:08 -06003564String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3565{
3566 bool matchFound = true;
3567 uint32_t dupeCounter = 0;
3568
3569 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3570 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3571
3572 // Loop over layers until we're sure there is no matching name
3573 while (matchFound) {
3574 matchFound = false;
3575 mDrawingState.traverseInZOrder([&](Layer* layer) {
3576 if (layer->getName() == uniqueName) {
3577 matchFound = true;
3578 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3579 }
3580 });
3581 }
3582
3583 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3584
3585 return uniqueName;
3586}
3587
David Sodman0c69cad2017-08-21 12:12:51 -07003588status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003589 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3590 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003591{
3592 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003593 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003594 case PIXEL_FORMAT_TRANSPARENT:
3595 case PIXEL_FORMAT_TRANSLUCENT:
3596 format = PIXEL_FORMAT_RGBA_8888;
3597 break;
3598 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003599 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003600 break;
3601 }
3602
David Sodman0c69cad2017-08-21 12:12:51 -07003603 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3604 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003605 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003606 *handle = layer->getHandle();
3607 *gbp = layer->getProducer();
3608 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003609 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003610
David Sodman0c69cad2017-08-21 12:12:51 -07003611 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003612 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003613}
3614
chaviw13fdc492017-06-27 12:40:18 -07003615status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003616 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003617 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003618{
chaviw13fdc492017-06-27 12:40:18 -07003619 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003620 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003621 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003622}
3623
Mathias Agopianac9fa422013-02-11 16:40:36 -08003624status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003625{
Robert Carr9524cb32017-02-13 11:32:32 -08003626 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003627 status_t err = NO_ERROR;
3628 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003629 if (l != nullptr) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003630 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003631 err = removeLayer(l);
3632 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3633 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003634 }
3635 return err;
3636}
3637
Mathias Agopian13127d82013-03-05 17:47:11 -08003638status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003639{
Mathias Agopian67106042013-03-14 19:18:13 -07003640 // called by ~LayerCleaner() when all references to the IBinder (handle)
3641 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003642 sp<Layer> l = layer.promote();
3643 if (l == nullptr) {
3644 // The layer has already been removed, carry on
3645 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003646 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003647 // If we have a parent, then we can continue to live as long as it does.
3648 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003649}
3650
Mathias Agopianb60314a2012-04-10 22:09:54 -07003651// ---------------------------------------------------------------------------
3652
Andy McFadden13a082e2012-08-24 10:16:42 -07003653void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003654 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003655 Vector<ComposerState> state;
3656 Vector<DisplayState> displays;
3657 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003658 d.what = DisplayState::eDisplayProjectionChanged |
3659 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003660 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003661 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003662 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003663 d.frame.makeInvalid();
3664 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003665 d.width = 0;
3666 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003667 displays.add(d);
3668 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003669 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3670 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003671
David Sodman105b7dc2017-11-04 20:28:14 -07003672 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003673 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003674 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003675
Brian Andersond0010582017-03-07 13:20:31 -08003676 // Use phase of 0 since phase is not known.
3677 // Use latency of 0, which will snap to the ideal latency.
3678 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003679}
3680
3681void SurfaceFlinger::initializeDisplays() {
3682 class MessageScreenInitialized : public MessageBase {
3683 SurfaceFlinger* flinger;
3684 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003685 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003686 virtual bool handler() {
3687 flinger->onInitializeDisplays();
3688 return true;
3689 }
3690 };
3691 sp<MessageBase> msg = new MessageScreenInitialized(this);
3692 postMessageAsync(msg); // we may be called from main thread, use async message
3693}
3694
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003695void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003696 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003697 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3698 this);
3699 int32_t type = hw->getDisplayType();
3700 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003701
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003702 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003703 return;
3704 }
3705
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003706 hw->setPowerMode(mode);
3707 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3708 ALOGW("Trying to set power mode for virtual display");
3709 return;
3710 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003711
Lloyd Pique4d234852018-01-22 17:21:36 -08003712 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003713 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003714 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3715 if (idx < 0) {
3716 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3717 return;
3718 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003719 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003720 }
3721
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003722 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003723 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003724 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003725 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3726 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003727 // FIXME: eventthread only knows about the main display right now
3728 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003729 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003730 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003731
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003732 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003733 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003734 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003735
3736 struct sched_param param = {0};
3737 param.sched_priority = 1;
3738 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3739 ALOGW("Couldn't set SCHED_FIFO on display on");
3740 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003741 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003742 // Turn off the display
3743 struct sched_param param = {0};
3744 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3745 ALOGW("Couldn't set SCHED_OTHER on display off");
3746 }
3747
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003748 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3749 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003750 disableHardwareVsync(true); // also cancels any in-progress resync
3751
Mathias Agopiancde87a32012-09-13 14:09:01 -07003752 // FIXME: eventthread only knows about the main display right now
3753 mEventThread->onScreenReleased();
3754 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003755
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003756 getHwComposer().setPowerMode(type, mode);
3757 mVisibleRegionsDirty = true;
3758 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003759 } else if (mode == HWC_POWER_MODE_DOZE ||
3760 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003761 // Update display while dozing
3762 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003763 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3764 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003765 // FIXME: eventthread only knows about the main display right now
3766 mEventThread->onScreenAcquired();
3767 resyncToHardwareVsync(true);
3768 }
3769 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3770 // Leave display going to doze
3771 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3772 disableHardwareVsync(true); // also cancels any in-progress resync
3773 // FIXME: eventthread only knows about the main display right now
3774 mEventThread->onScreenReleased();
3775 }
3776 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003777 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003778 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003779 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003780 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003781 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003782}
3783
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003784void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3785 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003786 SurfaceFlinger& mFlinger;
3787 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003788 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003789 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003790 MessageSetPowerMode(SurfaceFlinger& flinger,
3791 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3792 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003793 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003794 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003795 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003796 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003797 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003798 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003799 ALOGW("Attempt to set power mode = %d for virtual display",
3800 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003801 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003802 mFlinger.setPowerModeInternal(
3803 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003804 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003805 return true;
3806 }
3807 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003808 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003809 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003810}
3811
3812// ---------------------------------------------------------------------------
3813
Lloyd Pique755e3192018-01-31 16:46:15 -08003814status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3815 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003816 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003817
Mathias Agopianbd115332013-04-18 16:41:04 -07003818 IPCThreadState* ipc = IPCThreadState::self();
3819 const int pid = ipc->getCallingPid();
3820 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003821
Mathias Agopianbd115332013-04-18 16:41:04 -07003822 if ((uid != AID_SHELL) &&
3823 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003824 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003825 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003826 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003827 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003828 // (this would indicate SF is stuck, but we want to be able to
3829 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003830 status_t err = mStateLock.timedLock(s2ns(1));
3831 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003832 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003833 result.appendFormat(
3834 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3835 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003836 }
3837
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003838 bool dumpAll = true;
3839 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003840 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003841
3842 if (asProto) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003843 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviwa3d7bd32017-11-03 09:41:53 -07003844 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3845 dumpAll = false;
3846 }
3847
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003848 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003849 if ((index < numArgs) &&
3850 (args[index] == String16("--list"))) {
3851 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003852 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003853 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003854 }
3855
3856 if ((index < numArgs) &&
3857 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003858 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003859 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003860 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003861 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003862
3863 if ((index < numArgs) &&
3864 (args[index] == String16("--latency-clear"))) {
3865 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003866 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003867 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003868 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003869
3870 if ((index < numArgs) &&
3871 (args[index] == String16("--dispsync"))) {
3872 index++;
3873 mPrimaryDispSync.dump(result);
3874 dumpAll = false;
3875 }
Dan Stozab90cf072015-03-05 11:05:59 -08003876
3877 if ((index < numArgs) &&
3878 (args[index] == String16("--static-screen"))) {
3879 index++;
3880 dumpStaticScreenStats(result);
3881 dumpAll = false;
3882 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003883
3884 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003885 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003886 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003887 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003888 dumpAll = false;
3889 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003890
3891 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3892 index++;
3893 dumpWideColorInfo(result);
3894 dumpAll = false;
3895 }
Yiwei Zhang068e31b2018-02-21 13:02:45 -08003896
3897 if ((index < numArgs) &&
3898 (args[index] == String16("--enable-layer-stats"))) {
3899 index++;
3900 mLayerStats.enable();
3901 dumpAll = false;
3902 }
3903
3904 if ((index < numArgs) &&
3905 (args[index] == String16("--disable-layer-stats"))) {
3906 index++;
3907 mLayerStats.disable();
3908 dumpAll = false;
3909 }
3910
3911 if ((index < numArgs) &&
3912 (args[index] == String16("--clear-layer-stats"))) {
3913 index++;
3914 mLayerStats.clear();
3915 dumpAll = false;
3916 }
3917
3918 if ((index < numArgs) &&
3919 (args[index] == String16("--dump-layer-stats"))) {
3920 index++;
3921 mLayerStats.dump(result);
3922 dumpAll = false;
3923 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003924 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003925
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003926 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003927 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003928 }
3929
Mathias Agopian9795c422009-08-26 16:36:26 -07003930 if (locked) {
3931 mStateLock.unlock();
3932 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003933 }
3934 write(fd, result.string(), result.size());
3935 return NO_ERROR;
3936}
3937
Dan Stozac7014012014-02-14 15:03:43 -08003938void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3939 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003940{
Robert Carr2047fae2016-11-28 14:09:09 -08003941 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003942 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003943 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003944}
3945
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003946void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003947 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003948{
3949 String8 name;
3950 if (index < args.size()) {
3951 name = String8(args[index]);
3952 index++;
3953 }
3954
David Sodman105b7dc2017-11-04 20:28:14 -07003955 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003956 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003957 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003958
3959 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003960 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003961 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003962 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003963 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003964 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003965 }
Robert Carr2047fae2016-11-28 14:09:09 -08003966 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003967 }
3968}
3969
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003970void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003971 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003972{
3973 String8 name;
3974 if (index < args.size()) {
3975 name = String8(args[index]);
3976 index++;
3977 }
3978
Robert Carr2047fae2016-11-28 14:09:09 -08003979 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003980 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003981 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003982 }
Robert Carr2047fae2016-11-28 14:09:09 -08003983 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003984
Svetoslavd85084b2014-03-20 10:28:31 -07003985 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003986}
3987
Jamie Gennis6547ff42013-07-16 20:12:42 -07003988// This should only be called from the main thread. Otherwise it would need
3989// the lock and should use mCurrentState rather than mDrawingState.
3990void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003991 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003992 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003993 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003994
3995 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3996}
3997
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003998void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003999{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004000 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004001
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004002 if (isLayerTripleBufferingDisabled())
4003 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004004
4005 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004006 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004007 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004008 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004009 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4010 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004011 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004012}
4013
Dan Stozab90cf072015-03-05 11:05:59 -08004014void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4015{
4016 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004017 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4018 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004019 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004020 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004021 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4022 b + 1, bucketTimeSec, percent);
4023 }
David Sodman4a36e932017-11-07 14:29:47 -08004024 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004025 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004026 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004027 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004028 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004029}
4030
Dan Stozae77c7662016-05-13 11:37:28 -07004031void SurfaceFlinger::recordBufferingStats(const char* layerName,
4032 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004033 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4034 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004035 for (const auto& segment : history) {
4036 if (!segment.usedThirdBuffer) {
4037 stats.twoBufferTime += segment.totalTime;
4038 }
4039 if (segment.occupancyAverage < 1.0f) {
4040 stats.doubleBufferedTime += segment.totalTime;
4041 } else if (segment.occupancyAverage < 2.0f) {
4042 stats.tripleBufferedTime += segment.totalTime;
4043 }
4044 ++stats.numSegments;
4045 stats.totalTime += segment.totalTime;
4046 }
4047}
4048
Brian Andersond6927fb2016-07-23 23:37:30 -07004049void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4050 result.appendFormat("Layer frame timestamps:\n");
4051
4052 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4053 const size_t count = currentLayers.size();
4054 for (size_t i=0 ; i<count ; i++) {
4055 currentLayers[i]->dumpFrameEvents(result);
4056 }
4057}
4058
Dan Stozae77c7662016-05-13 11:37:28 -07004059void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4060 result.append("Buffering stats:\n");
4061 result.append(" [Layer name] <Active time> <Two buffer> "
4062 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004063 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004064 typedef std::tuple<std::string, float, float, float> BufferTuple;
4065 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004066 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004067 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004068 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004069 if (stats.numSegments == 0) {
4070 continue;
4071 }
4072 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4073 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4074 stats.totalTime;
4075 float doubleBufferRatio = static_cast<float>(
4076 stats.doubleBufferedTime) / stats.totalTime;
4077 float tripleBufferRatio = static_cast<float>(
4078 stats.tripleBufferedTime) / stats.totalTime;
4079 sorted.insert({activeTime, {name, twoBufferRatio,
4080 doubleBufferRatio, tripleBufferRatio}});
4081 }
4082 for (const auto& sortedPair : sorted) {
4083 float activeTime = sortedPair.first;
4084 const BufferTuple& values = sortedPair.second;
4085 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4086 std::get<0>(values).c_str(), activeTime,
4087 std::get<1>(values), std::get<2>(values),
4088 std::get<3>(values));
4089 }
4090 result.append("\n");
4091}
4092
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004093void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4094 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004095 result.appendFormat("DisplayColorSetting: %d\n", mDisplayColorSetting);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004096
4097 // TODO: print out if wide-color mode is active or not
4098
4099 for (size_t d = 0; d < mDisplays.size(); d++) {
4100 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4101 int32_t hwcId = displayDevice->getHwcDisplayId();
4102 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4103 continue;
4104 }
4105
4106 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004107 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004108 for (auto&& mode : modes) {
4109 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4110 }
4111
Peiyong Lina52f0292018-03-14 17:26:31 -07004112 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004113 result.appendFormat(" Current color mode: %s (%d)\n",
4114 decodeColorMode(currentMode).c_str(), currentMode);
4115 }
4116 result.append("\n");
4117}
4118
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004119LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004120 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004121 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4122 const State& state = useDrawing ? mDrawingState : mCurrentState;
4123 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004124 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004125 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004126 });
4127
4128 return layersProto;
4129}
4130
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004131LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4132 LayersProto layersProto;
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004133 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004134
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004135 SizeProto* resolution = layersProto.mutable_resolution();
4136 resolution->set_w(displayDevice->getWidth());
4137 resolution->set_h(displayDevice->getHeight());
4138
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004139 layersProto.set_color_mode(decodeColorMode(displayDevice->getActiveColorMode()));
4140 layersProto.set_color_transform(decodeColorTransform(displayDevice->getColorTransform()));
4141 layersProto.set_global_transform(
4142 static_cast<int32_t>(displayDevice->getOrientationTransform()));
4143
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004144 mDrawingState.traverseInZOrder([&](Layer* layer) {
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004145 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004146 LayerProto* layerProto = layersProto.add_layers();
4147 layer->writeToProto(layerProto, hwcId);
4148 }
4149 });
4150
4151 return layersProto;
4152}
4153
Mathias Agopian74d211a2013-04-22 16:55:35 +02004154void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4155 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004156{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004157 bool colorize = false;
4158 if (index < args.size()
4159 && (args[index] == String16("--color"))) {
4160 colorize = true;
4161 index++;
4162 }
4163
4164 Colorizer colorizer(colorize);
4165
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004166 // figure out if we're stuck somewhere
4167 const nsecs_t now = systemTime();
4168 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4169 const nsecs_t inTransaction(mDebugInTransaction);
4170 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4171 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4172
4173 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004174 * Dump library configuration.
4175 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004176
4177 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004178 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004179 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004180 appendSfConfigString(result);
4181 appendUiConfigString(result);
4182 appendGuiConfigString(result);
4183 result.append("\n");
4184
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004185 result.append("\nWide-Color information:\n");
4186 dumpWideColorInfo(result);
4187
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004188 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004189 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004190 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004191 result.append(SyncFeatures::getInstance().toString());
4192 result.append("\n");
4193
David Sodman105b7dc2017-11-04 20:28:14 -07004194 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004195
Andy McFadden41d67d72014-04-25 16:58:34 -07004196 colorizer.bold(result);
4197 result.append("DispSync configuration: ");
4198 colorizer.reset(result);
Dan Stoza2713c302018-03-28 17:07:36 -07004199 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, early sf phase %" PRId64
4200 " ns, present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4201 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, mVsyncModulator.getEarlyPhaseOffset(),
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004202 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004203 result.append("\n");
4204
Dan Stozab90cf072015-03-05 11:05:59 -08004205 // Dump static screen stats
4206 result.append("\n");
4207 dumpStaticScreenStats(result);
4208 result.append("\n");
4209
Dan Stozae77c7662016-05-13 11:37:28 -07004210 dumpBufferingStats(result);
4211
Andy McFadden4803b742012-09-24 19:07:20 -07004212 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004213 * Dump the visible layer list
4214 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004215 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004216 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004217 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4218 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004219 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004220
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004221 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004222 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7794ec12018-03-14 13:28:39 -07004223 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004224 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004225
4226 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004227 * Dump Display state
4228 */
4229
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004230 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004231 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004232 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004233 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4234 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004235 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004236 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004237 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004238
4239 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004240 * Dump SurfaceFlinger global state
4241 */
4242
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004243 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004244 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004245 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004246
Mathias Agopian888c8222012-08-04 21:10:38 -07004247 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004248 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004249
David Sodmanbc815282017-11-05 18:57:52 -08004250 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004251
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004252 if (hw) {
4253 hw->undefinedRegion.dump(result, "undefinedRegion");
4254 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4255 hw->getOrientation(), hw->isDisplayOn());
4256 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004257 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004258 " last eglSwapBuffers() time: %f us\n"
4259 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004260 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004261 " refresh-rate : %f fps\n"
4262 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004263 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004264 " gpu_to_cpu_unsupported : %d\n"
4265 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004266 mLastSwapBufferTime/1000.0,
4267 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004268 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004269 1e9 / activeConfig->getVsyncPeriod(),
4270 activeConfig->getDpiX(),
4271 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004272 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004273
Mathias Agopian74d211a2013-04-22 16:55:35 +02004274 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004275 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004276
Mathias Agopian74d211a2013-04-22 16:55:35 +02004277 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004278 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004279
4280 /*
4281 * VSYNC state
4282 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004283 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004284 result.append("\n");
4285
4286 /*
4287 * HWC layer minidump
4288 */
4289 for (size_t d = 0; d < mDisplays.size(); d++) {
4290 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4291 int32_t hwcId = displayDevice->getHwcDisplayId();
4292 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4293 continue;
4294 }
4295
4296 result.appendFormat("Display %d HWC layers:\n", hwcId);
4297 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004298 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004299 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004300 });
Dan Stozae22aec72016-08-01 13:20:59 -07004301 result.append("\n");
4302 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004303
4304 /*
4305 * Dump HWComposer state
4306 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004307 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004308 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004309 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004310 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004311 result.appendFormat(" h/w composer %s\n",
4312 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004313 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004314
4315 /*
4316 * Dump gralloc state
4317 */
4318 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4319 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004320
4321 /*
4322 * Dump VrFlinger state if in use.
4323 */
4324 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4325 result.append("VrFlinger state:\n");
4326 result.append(mVrFlinger->Dump().c_str());
4327 result.append("\n");
4328 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004329}
4330
Mathias Agopian13127d82013-03-05 17:47:11 -08004331const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004332SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004333 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004334 wp<IBinder> dpy;
4335 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4336 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4337 dpy = mDisplays.keyAt(i);
4338 break;
4339 }
4340 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004341 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004342 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4343 // Just use the primary display so we have something to return
4344 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4345 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004346 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004347}
4348
Keun young Park63f165f2012-08-31 10:53:36 -07004349bool SurfaceFlinger::startDdmConnection()
4350{
4351 void* libddmconnection_dso =
4352 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4353 if (!libddmconnection_dso) {
4354 return false;
4355 }
4356 void (*DdmConnection_start)(const char* name);
4357 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004358 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004359 if (!DdmConnection_start) {
4360 dlclose(libddmconnection_dso);
4361 return false;
4362 }
4363 (*DdmConnection_start)(getServiceName());
4364 return true;
4365}
4366
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004367status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004368 switch (code) {
4369 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004370 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004371 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004372 case CLEAR_ANIMATION_FRAME_STATS:
4373 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004374 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004375 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004376 case ENABLE_VSYNC_INJECTIONS:
4377 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004378 {
4379 // codes that require permission check
4380 IPCThreadState* ipc = IPCThreadState::self();
4381 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004382 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004383 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004384 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004385 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004386 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004387 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004388 break;
4389 }
Robert Carr1db73f62016-12-21 12:58:51 -08004390 /*
4391 * Calling setTransactionState is safe, because you need to have been
4392 * granted a reference to Client* and Handle* to do anything with it.
4393 *
4394 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4395 */
4396 case SET_TRANSACTION_STATE:
4397 case CREATE_SCOPED_CONNECTION:
4398 {
4399 return OK;
4400 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004401 case CAPTURE_SCREEN:
4402 {
4403 // codes that require permission check
4404 IPCThreadState* ipc = IPCThreadState::self();
4405 const int pid = ipc->getCallingPid();
4406 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004407 if ((uid != AID_GRAPHICS) &&
4408 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004409 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004410 return PERMISSION_DENIED;
4411 }
4412 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004413 }
chaviwa76b2712017-09-20 12:02:26 -07004414 case CAPTURE_LAYERS: {
4415 IPCThreadState* ipc = IPCThreadState::self();
4416 const int pid = ipc->getCallingPid();
4417 const int uid = ipc->getCallingUid();
4418 if ((uid != AID_GRAPHICS) &&
4419 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4420 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4421 return PERMISSION_DENIED;
4422 }
4423 break;
4424 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004425 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004426 return OK;
4427}
4428
4429status_t SurfaceFlinger::onTransact(
4430 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4431{
4432 status_t credentialCheck = CheckTransactCodeCredentials(code);
4433 if (credentialCheck != OK) {
4434 return credentialCheck;
4435 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004436
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004437 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4438 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004439 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004440 IPCThreadState* ipc = IPCThreadState::self();
4441 const int uid = ipc->getCallingUid();
4442 if (CC_UNLIKELY(uid != AID_SYSTEM
4443 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004444 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004445 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004446 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004447 return PERMISSION_DENIED;
4448 }
4449 int n;
4450 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004451 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004452 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004453 return NO_ERROR;
4454 case 1002: // SHOW_UPDATES
4455 n = data.readInt32();
4456 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004457 invalidateHwcGeometry();
4458 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004459 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004460 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004461 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004462 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004463 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004464 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004465 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004466 setTransactionFlags(
4467 eTransactionNeeded|
4468 eDisplayTransactionNeeded|
4469 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004470 return NO_ERROR;
4471 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004472 case 1006:{ // send empty update
4473 signalRefresh();
4474 return NO_ERROR;
4475 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004476 case 1008: // toggle use of hw composer
4477 n = data.readInt32();
4478 mDebugDisableHWC = n ? 1 : 0;
4479 invalidateHwcGeometry();
4480 repaintEverything();
4481 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004482 case 1009: // toggle use of transform hint
4483 n = data.readInt32();
4484 mDebugDisableTransformHint = n ? 1 : 0;
4485 invalidateHwcGeometry();
4486 repaintEverything();
4487 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004488 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004489 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004490 reply->writeInt32(0);
4491 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004492 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004493 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004494 return NO_ERROR;
4495 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004496 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004497 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004498 return NO_ERROR;
4499 }
4500 case 1014: {
4501 // daltonize
4502 n = data.readInt32();
4503 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004504 case 1:
4505 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4506 break;
4507 case 2:
4508 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4509 break;
4510 case 3:
4511 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4512 break;
4513 default:
4514 mDaltonizer.setType(ColorBlindnessType::None);
4515 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004516 }
4517 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004518 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004519 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004520 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004521 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004522 invalidateHwcGeometry();
4523 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004524 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004525 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004526 case 1015: {
4527 // apply a color matrix
4528 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004529 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004530 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004531 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004532 for (size_t j = 0; j < 4; j++) {
4533 mColorMatrix[i][j] = data.readFloat();
4534 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004535 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004536 } else {
4537 mColorMatrix = mat4();
4538 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004539
4540 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4541 // the division by w in the fragment shader
4542 float4 lastRow(transpose(mColorMatrix)[3]);
4543 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4544 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4545 }
4546
Alan Viverette9c5a3332013-09-12 20:04:35 -07004547 invalidateHwcGeometry();
4548 repaintEverything();
4549 return NO_ERROR;
4550 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004551 // This is an experimental interface
4552 // Needs to be shifted to proper binder interface when we productize
4553 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004554 n = data.readInt32();
4555 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004556 return NO_ERROR;
4557 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004558 case 1017: {
4559 n = data.readInt32();
4560 mForceFullDamage = static_cast<bool>(n);
4561 return NO_ERROR;
4562 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004563 case 1018: { // Modify Choreographer's phase offset
4564 n = data.readInt32();
4565 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4566 return NO_ERROR;
4567 }
4568 case 1019: { // Modify SurfaceFlinger's phase offset
4569 n = data.readInt32();
4570 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4571 return NO_ERROR;
4572 }
Irvel468051e2016-06-13 16:44:44 -07004573 case 1020: { // Layer updates interceptor
4574 n = data.readInt32();
4575 if (n) {
4576 ALOGV("Interceptor enabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004577 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004578 }
4579 else{
4580 ALOGV("Interceptor disabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004581 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004582 }
4583 return NO_ERROR;
4584 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004585 case 1021: { // Disable HWC virtual displays
4586 n = data.readInt32();
4587 mUseHwcVirtualDisplays = !n;
4588 return NO_ERROR;
4589 }
Romain Guy0147a172017-06-01 13:53:56 -07004590 case 1022: { // Set saturation boost
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004591 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004592
4593 invalidateHwcGeometry();
4594 repaintEverything();
4595 return NO_ERROR;
4596 }
Romain Guy54f154a2017-10-24 21:40:32 +01004597 case 1023: { // Set native mode
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004598 int32_t value = data.readInt32();
4599 if (value > 2) {
4600 return BAD_VALUE;
4601 }
4602 if (value == 2 && !mBuiltinDisplaySupportsEnhance) {
4603 return BAD_VALUE;
4604 }
Romain Guy54f154a2017-10-24 21:40:32 +01004605
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004606 mDisplayColorSetting = toDisplayColorSetting(value);
Romain Guy54f154a2017-10-24 21:40:32 +01004607 invalidateHwcGeometry();
4608 repaintEverything();
4609 return NO_ERROR;
4610 }
4611 case 1024: { // Is wide color gamut rendering/color management supported?
4612 reply->writeBool(hasWideColorDisplay);
4613 return NO_ERROR;
4614 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004615 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004616 n = data.readInt32();
4617 if (n) {
4618 ALOGV("LayerTracing enabled");
4619 mTracing.enable();
4620 doTracing("tracing.enable");
4621 reply->writeInt32(NO_ERROR);
4622 } else {
4623 ALOGV("LayerTracing disabled");
4624 status_t err = mTracing.disable();
4625 reply->writeInt32(err);
4626 }
4627 return NO_ERROR;
4628 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004629 case 1026: { // Get layer tracing status
4630 reply->writeBool(mTracing.isEnabled());
4631 return NO_ERROR;
4632 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004633 // Is a DisplayColorSetting supported?
4634 case 1027: {
4635 int32_t value = data.readInt32();
4636 switch (value) {
4637 case 0:
4638 reply->writeBool(hasWideColorDisplay);
4639 return NO_ERROR;
4640 case 1:
4641 reply->writeBool(true);
4642 return NO_ERROR;
4643 case 2:
4644 reply->writeBool(mBuiltinDisplaySupportsEnhance);
4645 return NO_ERROR;
4646 default:
4647 return BAD_VALUE;
4648 }
4649 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004650 }
4651 }
4652 return err;
4653}
4654
Steven Thomas6d8110b2017-08-31 18:24:21 -07004655void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004656 android_atomic_or(1, &mRepaintEverything);
4657 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004658}
4659
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004660// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4661class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004662public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004663 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4664 ~WindowDisconnector() {
4665 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004666 }
4667
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004668private:
4669 ANativeWindow* mWindow;
4670 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004671};
4672
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004673status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4674 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4675 int32_t minLayerZ, int32_t maxLayerZ,
4676 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004677 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004678 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004679
chaviwa76b2712017-09-20 12:02:26 -07004680 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4681
4682 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004683 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4684
chaviwa76b2712017-09-20 12:02:26 -07004685 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4686
4687 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4688 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004689 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004690}
4691
4692status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004693 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004694 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004695 ATRACE_CALL();
4696
4697 class LayerRenderArea : public RenderArea {
4698 public:
Robert Carr578038f2018-03-09 12:25:24 -08004699 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4700 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004701 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004702 mLayer(layer),
4703 mCrop(crop),
4704 mFlinger(flinger),
4705 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004706 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004707 Rect getBounds() const override {
4708 const Layer::State& layerState(mLayer->getDrawingState());
4709 return Rect(layerState.active.w, layerState.active.h);
4710 }
4711 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4712 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4713 bool isSecure() const override { return false; }
4714 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004715 Rect getSourceCrop() const override {
4716 if (mCrop.isEmpty()) {
4717 return getBounds();
4718 } else {
4719 return mCrop;
4720 }
4721 }
4722 bool getWideColorSupport() const override { return false; }
4723 Dataspace getDataSpace() const override { return Dataspace::UNKNOWN; }
Robert Carr578038f2018-03-09 12:25:24 -08004724
4725 class ReparentForDrawing {
4726 public:
4727 const sp<Layer>& oldParent;
4728 const sp<Layer>& newParent;
4729
4730 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4731 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004732 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004733 }
Robert Carr15eae092018-03-23 13:43:53 -07004734 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004735 };
4736
4737 void render(std::function<void()> drawLayers) override {
4738 if (!mChildrenOnly) {
4739 mTransform = mLayer->getTransform().inverse();
4740 drawLayers();
4741 } else {
4742 Rect bounds = getBounds();
4743 screenshotParentLayer =
4744 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4745 bounds.getWidth(), bounds.getHeight(), 0);
4746
4747 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4748 drawLayers();
4749 }
4750 }
chaviwa76b2712017-09-20 12:02:26 -07004751
chaviwa76b2712017-09-20 12:02:26 -07004752 private:
chaviw7206d492017-11-10 16:16:12 -08004753 const sp<Layer> mLayer;
4754 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004755
4756 // In the "childrenOnly" case we reparent the children to a screenshot
4757 // layer which has no properties set and which does not draw.
4758 sp<ContainerLayer> screenshotParentLayer;
4759 Transform mTransform;
4760
4761 SurfaceFlinger* mFlinger;
4762 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004763 };
4764
4765 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4766 auto parent = layerHandle->owner.promote();
4767
chaviw7206d492017-11-10 16:16:12 -08004768 if (parent == nullptr || parent->isPendingRemoval()) {
4769 ALOGE("captureLayers called with a removed parent");
4770 return NAME_NOT_FOUND;
4771 }
4772
Robert Carr578038f2018-03-09 12:25:24 -08004773 const int uid = IPCThreadState::self()->getCallingUid();
4774 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4775 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4776 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4777 return PERMISSION_DENIED;
4778 }
4779
chaviw7206d492017-11-10 16:16:12 -08004780 Rect crop(sourceCrop);
4781 if (sourceCrop.width() <= 0) {
4782 crop.left = 0;
4783 crop.right = parent->getCurrentState().active.w;
4784 }
4785
4786 if (sourceCrop.height() <= 0) {
4787 crop.top = 0;
4788 crop.bottom = parent->getCurrentState().active.h;
4789 }
4790
4791 int32_t reqWidth = crop.width() * frameScale;
4792 int32_t reqHeight = crop.height() * frameScale;
4793
Robert Carr578038f2018-03-09 12:25:24 -08004794 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004795
Robert Carr578038f2018-03-09 12:25:24 -08004796 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004797 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4798 if (!layer->isVisible()) {
4799 return;
Robert Carr578038f2018-03-09 12:25:24 -08004800 } else if (childrenOnly && layer == parent.get()) {
4801 return;
chaviwa76b2712017-09-20 12:02:26 -07004802 }
4803 visitor(layer);
4804 });
4805 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004806 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004807}
4808
4809status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4810 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004811 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004812 bool useIdentityTransform) {
4813 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004814
chaviwa76b2712017-09-20 12:02:26 -07004815 renderArea.updateDimensions();
4816
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004817 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4818 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4819 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4820 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004821
4822 // This mutex protects syncFd and captureResult for communication of the return values from the
4823 // main thread back to this Binder thread
4824 std::mutex captureMutex;
4825 std::condition_variable captureCondition;
4826 std::unique_lock<std::mutex> captureLock(captureMutex);
4827 int syncFd = -1;
4828 std::optional<status_t> captureResult;
4829
Robert Carr03480e22018-01-04 16:02:06 -08004830 const int uid = IPCThreadState::self()->getCallingUid();
4831 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4832
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004833 sp<LambdaMessage> message = new LambdaMessage([&]() {
4834 // If there is a refresh pending, bug out early and tell the binder thread to try again
4835 // after the refresh.
4836 if (mRefreshPending) {
4837 ATRACE_NAME("Skipping screenshot for now");
4838 std::unique_lock<std::mutex> captureLock(captureMutex);
4839 captureResult = std::make_optional<status_t>(EAGAIN);
4840 captureCondition.notify_one();
4841 return;
4842 }
4843
4844 status_t result = NO_ERROR;
4845 int fd = -1;
4846 {
4847 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004848 renderArea.render([&]() {
4849 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4850 useIdentityTransform, forSystem, &fd);
4851 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004852 }
4853
4854 {
4855 std::unique_lock<std::mutex> captureLock(captureMutex);
4856 syncFd = fd;
4857 captureResult = std::make_optional<status_t>(result);
4858 captureCondition.notify_one();
4859 }
4860 });
4861
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004862 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004863 if (result == NO_ERROR) {
4864 captureCondition.wait(captureLock, [&]() { return captureResult; });
4865 while (*captureResult == EAGAIN) {
4866 captureResult.reset();
4867 result = postMessageAsync(message);
4868 if (result != NO_ERROR) {
4869 return result;
4870 }
4871 captureCondition.wait(captureLock, [&]() { return captureResult; });
4872 }
4873 result = *captureResult;
4874 }
4875
4876 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004877 sync_wait(syncFd, -1);
4878 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004879 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004880
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004881 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004882}
4883
chaviwa76b2712017-09-20 12:02:26 -07004884void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4885 TraverseLayersFunction traverseLayers, bool yswap,
4886 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004887 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004888
Lloyd Pique144e1162017-12-20 16:44:52 -08004889 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004890
4891 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004892 const auto raWidth = renderArea.getWidth();
4893 const auto raHeight = renderArea.getHeight();
4894
4895 const auto reqWidth = renderArea.getReqWidth();
4896 const auto reqHeight = renderArea.getReqHeight();
4897 Rect sourceCrop = renderArea.getSourceCrop();
4898
4899 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4900 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004901
Dan Stozac1879002014-05-22 15:59:05 -07004902 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004903 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004904 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004905 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004906 }
4907
4908 // ensure that sourceCrop is inside screen
4909 if (sourceCrop.left < 0) {
4910 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4911 }
chaviwa76b2712017-09-20 12:02:26 -07004912 if (sourceCrop.right > raWidth) {
4913 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004914 }
4915 if (sourceCrop.top < 0) {
4916 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4917 }
chaviwa76b2712017-09-20 12:02:26 -07004918 if (sourceCrop.bottom > raHeight) {
4919 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004920 }
4921
Peiyong Lin34beb7a2018-03-28 11:57:12 -07004922 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004923 if (renderArea.getWideColorSupport()) {
4924 outputDataspace = renderArea.getDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004925 }
4926 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Romain Guy88d37dd2017-05-26 17:57:05 -07004927
Mathias Agopian180f10d2013-04-10 22:55:41 -07004928 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004929 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004930
4931 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004932 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4933 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004934 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004935
chaviw50da5042018-04-09 13:49:37 -07004936 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004937 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07004938 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004939
chaviwa76b2712017-09-20 12:02:26 -07004940 traverseLayers([&](Layer* layer) {
4941 if (filtering) layer->setFiltering(true);
4942 layer->draw(renderArea, useIdentityTransform);
4943 if (filtering) layer->setFiltering(false);
4944 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004945}
4946
chaviwa76b2712017-09-20 12:02:26 -07004947status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4948 TraverseLayersFunction traverseLayers,
4949 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004950 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08004951 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07004952 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004953 ATRACE_CALL();
4954
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004955 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004956
4957 traverseLayers([&](Layer* layer) {
4958 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4959 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004960
Robert Carr03480e22018-01-04 16:02:06 -08004961 // We allow the system server to take screenshots of secure layers for
4962 // use in situations like the Screen-rotation animation and place
4963 // the impetus on WindowManager to not persist them.
4964 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004965 ALOGW("FB is protected: PERMISSION_DENIED");
4966 return PERMISSION_DENIED;
4967 }
4968
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004969 // this binds the given EGLImage as a framebuffer for the
4970 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08004971 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08004972 if (bufferBond.getStatus() != NO_ERROR) {
4973 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004974 return INVALID_OPERATION;
4975 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004976
Dan Stozaabcda352017-06-01 14:37:39 -07004977 // this will in fact render into our dequeued buffer
4978 // via an FBO, which means we didn't have to create
4979 // an EGLSurface and therefore we're not
4980 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004981 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004982
Dan Stozaabcda352017-06-01 14:37:39 -07004983 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08004984 getRenderEngine().finish();
4985 *outSyncFd = -1;
4986
chaviwa76b2712017-09-20 12:02:26 -07004987 const auto reqWidth = renderArea.getReqWidth();
4988 const auto reqHeight = renderArea.getReqHeight();
4989
Dan Stozaabcda352017-06-01 14:37:39 -07004990 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4991 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004992 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004993 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08004994 } else {
4995 base::unique_fd syncFd = getRenderEngine().flush();
4996 if (syncFd < 0) {
4997 getRenderEngine().finish();
4998 }
4999 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005000 }
5001
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005002 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005003}
5004
Mathias Agopiand5556842013-09-19 17:08:37 -07005005void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005006 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005007 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005008 for (size_t y = 0; y < h; y++) {
5009 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5010 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005011 if (p[x] != 0xFF000000) return;
5012 }
5013 }
chaviwa76b2712017-09-20 12:02:26 -07005014 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005015
Robert Carr2047fae2016-11-28 14:09:09 -08005016 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005017 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005018 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005019 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5020 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5021 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5022 static_cast<float>(state.color.a));
5023 i++;
5024 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005025 }
5026}
5027
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005028// ---------------------------------------------------------------------------
5029
Dan Stoza412903f2017-04-27 13:42:17 -07005030void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5031 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005032}
5033
Dan Stoza412903f2017-04-27 13:42:17 -07005034void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5035 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005036}
5037
chaviwa76b2712017-09-20 12:02:26 -07005038void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
5039 int32_t maxLayerZ,
5040 const LayerVector::Visitor& visitor) {
5041 // We loop through the first level of layers without traversing,
5042 // as we need to interpret min/max layer Z in the top level Z space.
5043 for (const auto& layer : mDrawingState.layersSortedByZ) {
5044 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5045 continue;
5046 }
5047 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005048 // relative layers are traversed in Layer::traverseInZOrder
5049 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005050 continue;
5051 }
5052 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005053 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5054 return;
5055 }
chaviwa76b2712017-09-20 12:02:26 -07005056 if (!layer->isVisible()) {
5057 return;
5058 }
5059 visitor(layer);
5060 });
5061 }
5062}
5063
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005064}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005065
5066
5067#if defined(__gl_h_)
5068#error "don't include gl/gl.h in this file"
5069#endif
5070
5071#if defined(__gl2_h_)
5072#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005073#endif