blob: e3a47069f8afac394f1d0e8bcb6ea93116510fbd [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 Linfb069302018-04-25 14:34:31 -07001122 // At this point the DisplayDeivce should already be set up,
1123 // meaning the luminance information is already queried from
1124 // hardware composer and stored properly.
1125 const HdrCapabilities& capabilities = displayDevice->getHdrCapabilities();
1126 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1127 capabilities.getDesiredMaxLuminance(),
1128 capabilities.getDesiredMaxAverageLuminance(),
1129 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001130
1131 return NO_ERROR;
1132}
1133
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001134status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001135 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1136 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001137
Chia-I Wu90f669f2017-10-05 14:24:41 -07001138 if (mInjectVSyncs == enable) {
1139 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001140 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001141
1142 if (enable) {
1143 ALOGV("VSync Injections enabled");
1144 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001145 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique0fcde1b2017-12-20 16:50:21 -08001146 mInjectorEventThread =
1147 std::make_unique<impl::EventThread>(mVSyncInjector.get(), *this, false,
1148 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001149 }
Lloyd Pique9123ae52018-01-22 17:14:00 -08001150 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001151 } else {
1152 ALOGV("VSync Injections disabled");
Lloyd Pique9123ae52018-01-22 17:14:00 -08001153 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001154 }
1155
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001156 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001157 });
1158 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001159 return NO_ERROR;
1160}
1161
1162status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001163 Mutex::Autolock _l(mStateLock);
1164
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001165 if (!mInjectVSyncs) {
1166 ALOGE("VSync Injections not enabled");
1167 return BAD_VALUE;
1168 }
1169 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1170 ALOGV("Injecting VSync inside SurfaceFlinger");
1171 mVSyncInjector->onInjectSyncEvent(when);
1172 }
1173 return NO_ERROR;
1174}
1175
Lloyd Pique755e3192018-01-31 16:46:15 -08001176status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1177 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001178 IPCThreadState* ipc = IPCThreadState::self();
1179 const int pid = ipc->getCallingPid();
1180 const int uid = ipc->getCallingUid();
1181 if ((uid != AID_SHELL) &&
1182 !PermissionCache::checkPermission(sDump, pid, uid)) {
1183 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1184 return PERMISSION_DENIED;
1185 }
1186
1187 // Try to acquire a lock for 1s, fail gracefully
1188 const status_t err = mStateLock.timedLock(s2ns(1));
1189 const bool locked = (err == NO_ERROR);
1190 if (!locked) {
1191 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1192 return TIMED_OUT;
1193 }
1194
1195 outLayers->clear();
1196 mCurrentState.traverseInZOrder([&](Layer* layer) {
1197 outLayers->push_back(layer->getLayerDebugInfo());
1198 });
1199
1200 mStateLock.unlock();
1201 return NO_ERROR;
1202}
1203
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001204// ----------------------------------------------------------------------------
1205
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001206sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1207 ISurfaceComposer::VsyncSource vsyncSource) {
1208 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1209 return mSFEventThread->createEventConnection();
1210 } else {
1211 return mEventThread->createEventConnection();
1212 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001213}
1214
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001215// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001216
1217void SurfaceFlinger::waitForEvent() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001218 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001219}
1220
1221void SurfaceFlinger::signalTransaction() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001222 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001223}
1224
1225void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001226 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001227}
1228
1229void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001230 mRefreshPending = true;
Lloyd Pique9123ae52018-01-22 17:14:00 -08001231 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001232}
1233
1234status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001235 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001236 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001237}
1238
1239status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001240 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001241 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001242 if (res == NO_ERROR) {
1243 msg->wait();
1244 }
1245 return res;
1246}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001247
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001248void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001249 do {
1250 waitForEvent();
1251 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001252}
1253
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001254void SurfaceFlinger::enableHardwareVsync() {
1255 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001256 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001257 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001258 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1259 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001260 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001261 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001262}
1263
Jesse Hall948fe0c2013-10-14 12:56:09 -07001264void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001265 Mutex::Autolock _l(mHWVsyncLock);
1266
Jesse Hall948fe0c2013-10-14 12:56:09 -07001267 if (makeAvailable) {
1268 mHWVsyncAvailable = true;
1269 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001270 // Hardware vsync is not currently available, so abort the resync
1271 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001272 return;
1273 }
1274
David Sodman105b7dc2017-11-04 20:28:14 -07001275 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001276 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001277
1278 mPrimaryDispSync.reset();
1279 mPrimaryDispSync.setPeriod(period);
1280
1281 if (!mPrimaryHWVsyncEnabled) {
1282 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001283 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1284 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001285 mPrimaryHWVsyncEnabled = true;
1286 }
1287}
1288
Jesse Hall948fe0c2013-10-14 12:56:09 -07001289void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001290 Mutex::Autolock _l(mHWVsyncLock);
1291 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001292 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1293 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001294 mPrimaryDispSync.endResync();
1295 mPrimaryHWVsyncEnabled = false;
1296 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001297 if (makeUnavailable) {
1298 mHWVsyncAvailable = false;
1299 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001300}
1301
Tim Murray4a4e4a22016-04-19 16:29:23 +00001302void SurfaceFlinger::resyncWithRateLimit() {
1303 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001304
1305 // No explicit locking is needed here since EventThread holds a lock while calling this method
1306 static nsecs_t sLastResyncAttempted = 0;
1307 const nsecs_t now = systemTime();
1308 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001309 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001310 }
Dan Stoza57164302017-05-08 14:03:54 -07001311 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001312}
1313
Steven Thomasb02664d2017-07-26 18:48:28 -07001314void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1315 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001316 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001317 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001318 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001319 return;
1320 }
1321
1322 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001323 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001324 return;
1325 }
1326
Jamie Gennisd1700752013-10-14 12:22:52 -07001327 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001328
Jamie Gennisd1700752013-10-14 12:22:52 -07001329 { // Scope for the lock
1330 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001331 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001332 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001333 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001334 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001335
1336 if (needsHwVsync) {
1337 enableHardwareVsync();
1338 } else {
1339 disableHardwareVsync(false);
1340 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001341}
1342
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001343void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001344 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1345 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001346}
1347
Lloyd Pique715a2c12017-12-14 17:18:08 -08001348void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1349 HWC2::Connection connection) {
1350 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1351 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001352
Lloyd Piqueba04e622017-12-14 17:11:26 -08001353 // Ignore events that do not have the right sequenceId.
1354 if (sequenceId != getBE().mComposerSequenceId) {
1355 return;
1356 }
1357
Steven Thomasb02664d2017-07-26 18:48:28 -07001358 // Only lock if we're not on the main thread. This function is normally
1359 // called on a hwbinder thread, but for the primary display it's called on
1360 // the main thread with the state lock already held, so don't attempt to
1361 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001362 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001363
Lloyd Pique715a2c12017-12-14 17:18:08 -08001364 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001365
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001366 if (std::this_thread::get_id() == mMainThreadId) {
1367 // Process all pending hot plug events immediately if we are on the main thread.
1368 processDisplayHotplugEventsLocked();
1369 }
1370
Lloyd Piqueba04e622017-12-14 17:11:26 -08001371 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001372}
1373
Steven Thomasb02664d2017-07-26 18:48:28 -07001374void SurfaceFlinger::onRefreshReceived(int sequenceId,
1375 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001376 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001377 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001378 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001379 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001380 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001381}
1382
Dan Stoza9e56aa02015-11-02 13:00:03 -08001383void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001384 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001385 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001386 getHwComposer().setVsyncEnabled(disp,
1387 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001388}
1389
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001390// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001391void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001392 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001393 // Clear the drawing state so that the logic inside of
1394 // handleTransactionLocked will fire. It will determine the delta between
1395 // mCurrentState and mDrawingState and re-apply all changes when we make the
1396 // transition.
1397 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001398 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001399 mDisplays.clear();
1400}
1401
Steven Thomas050b2c82017-03-06 11:45:16 -08001402void SurfaceFlinger::updateVrFlinger() {
1403 if (!mVrFlinger)
1404 return;
1405 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001406 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001407 return;
1408 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001409
David Sodman105b7dc2017-11-04 20:28:14 -07001410 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001411 ALOGE("Vr flinger is only supported for remote hardware composer"
1412 " service connections. Ignoring request to transition to vr"
1413 " flinger.");
1414 mVrFlingerRequestsDisplay = false;
1415 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001416 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001417
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001418 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001419
Steven Thomasb02664d2017-07-26 18:48:28 -07001420 int currentDisplayPowerMode = getDisplayDeviceLocked(
1421 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001422
Steven Thomasb02664d2017-07-26 18:48:28 -07001423 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001424 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001425 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001426
Steven Thomasb02664d2017-07-26 18:48:28 -07001427 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001428 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001429 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1430 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001431 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001432
David Sodman105b7dc2017-11-04 20:28:14 -07001433 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1434 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001435
1436 if (vrFlingerRequestsDisplay) {
1437 mVrFlinger->GrantDisplayOwnership();
1438 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001439 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001440 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001441
1442 mVisibleRegionsDirty = true;
1443 invalidateHwcGeometry();
1444
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001445 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001446 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1447 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1448 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001449
Steven Thomasb02664d2017-07-26 18:48:28 -07001450 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001451 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001452 const nsecs_t period = activeConfig->getVsyncPeriod();
1453 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001454
Steven Thomasb02664d2017-07-26 18:48:28 -07001455 // Use phase of 0 since phase is not known.
1456 // Use latency of 0, which will snap to the ideal latency.
1457 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001458
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001459 android_atomic_or(1, &mRepaintEverything);
1460 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001461}
1462
Mathias Agopian4fec8732012-06-29 14:12:52 -07001463void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001464 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001465 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001466 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001467 bool frameMissed = !mHadClientComposition &&
1468 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001469 (mPreviousPresentFence->getSignalTime() ==
1470 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001471 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001472 if (mPropagateBackpressure && frameMissed) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001473 mTimeStats.incrementMissedFrames(true);
Dan Stoza50182882016-07-08 12:02:20 -07001474 signalLayerUpdate();
1475 break;
1476 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001477 if (frameMissed) {
1478 mTimeStats.incrementMissedFrames(false);
1479 }
Dan Stoza50182882016-07-08 12:02:20 -07001480
Steven Thomas050b2c82017-03-06 11:45:16 -08001481 // Now that we're going to make it to the handleMessageTransaction()
1482 // call below it's safe to call updateVrFlinger(), which will
1483 // potentially trigger a display handoff.
1484 updateVrFlinger();
1485
Dan Stoza6b9454d2014-11-07 16:00:59 -08001486 bool refreshNeeded = handleMessageTransaction();
1487 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001488 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001489 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001490 // Signal a refresh if a transaction modified the window state,
1491 // a new buffer was latched, or if HWC has requested a full
1492 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001493 signalRefresh();
1494 }
1495 break;
1496 }
1497 case MessageQueue::REFRESH: {
1498 handleMessageRefresh();
1499 break;
1500 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001501 }
1502}
1503
Dan Stoza6b9454d2014-11-07 16:00:59 -08001504bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001505 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001506 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001507 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001508 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001509 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001510 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001511}
1512
Dan Stoza6b9454d2014-11-07 16:00:59 -08001513bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001514 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001515 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001516}
1517
1518void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001519 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001520
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001521 mRefreshPending = false;
1522
Pablo Ceballos40845df2016-01-25 17:41:15 -08001523 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001524
Brian Andersond6927fb2016-07-23 23:37:30 -07001525 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001526 rebuildLayerStacks();
1527 setUpHWComposer();
1528 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001529 doTracing("handleRefresh");
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001530 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001531 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001532 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001533
David Sodman105b7dc2017-11-04 20:28:14 -07001534 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001535
1536 mHadClientComposition = false;
1537 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1538 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1539 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001540 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001541 }
Dan Stoza2713c302018-03-28 17:07:36 -07001542 mVsyncModulator.setLastFrameUsedRenderEngine(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001543
Dan Stoza9e56aa02015-11-02 13:00:03 -08001544 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001545}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001546
Mathias Agopiancd60f992012-08-16 16:28:27 -07001547void SurfaceFlinger::doDebugFlashRegions()
1548{
1549 // is debugging enabled
1550 if (CC_LIKELY(!mDebugRegion))
1551 return;
1552
1553 const bool repaintEverything = mRepaintEverything;
1554 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1555 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001556 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001557 // transform the dirty region into this screen's coordinate space
1558 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1559 if (!dirtyRegion.isEmpty()) {
1560 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001561 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001562
1563 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001564 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001565 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001566 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1567
Mathias Agopianda27af92012-09-13 18:17:13 -07001568 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001569 }
1570 }
1571 }
1572
1573 postFramebuffer();
1574
1575 if (mDebugRegion > 1) {
1576 usleep(mDebugRegion * 1000);
1577 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001578
Dan Stoza9e56aa02015-11-02 13:00:03 -08001579 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001580 auto& displayDevice = mDisplays[displayId];
1581 if (!displayDevice->isDisplayOn()) {
1582 continue;
1583 }
1584
David Sodman105b7dc2017-11-04 20:28:14 -07001585 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1586 ALOGE_IF(result != NO_ERROR,
1587 "prepareFrame for display %zd failed:"
1588 " %d (%s)",
1589 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001590 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001591}
1592
Adrian Roos1e1a1282017-11-01 19:05:31 +01001593void SurfaceFlinger::doTracing(const char* where) {
1594 ATRACE_CALL();
1595 ATRACE_NAME(where);
1596 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001597 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001598 }
1599}
1600
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001601void SurfaceFlinger::logLayerStats() {
1602 ATRACE_CALL();
1603 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1604 int32_t hwcId = -1;
1605 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1606 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1607 if (displayDevice->isPrimary()) {
1608 hwcId = displayDevice->getHwcDisplayId();
1609 break;
1610 }
1611 }
1612 if (hwcId < 0) {
1613 ALOGE("LayerStats: Hmmm, no primary display?");
1614 return;
1615 }
1616 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1617 }
1618}
1619
Brian Andersond6927fb2016-07-23 23:37:30 -07001620void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001621{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001622 ATRACE_CALL();
1623 ALOGV("preComposition");
1624
Mathias Agopiancd60f992012-08-16 16:28:27 -07001625 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001626 mDrawingState.traverseInZOrder([&](Layer* layer) {
1627 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001628 needExtraInvalidate = true;
1629 }
Robert Carr2047fae2016-11-28 14:09:09 -08001630 });
1631
Mathias Agopiancd60f992012-08-16 16:28:27 -07001632 if (needExtraInvalidate) {
1633 signalLayerUpdate();
1634 }
1635}
1636
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001637void SurfaceFlinger::updateCompositorTiming(
1638 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1639 std::shared_ptr<FenceTime>& presentFenceTime) {
1640 // Update queue of past composite+present times and determine the
1641 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001642 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001643 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001644 while (!getBE().mCompositePresentTimes.empty()) {
1645 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001646 // Cached values should have been updated before calling this method,
1647 // which helps avoid duplicate syscalls.
1648 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1649 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1650 break;
1651 }
1652 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001653 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001654 }
1655
1656 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001657 while (getBE().mCompositePresentTimes.size() > 16) {
1658 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001659 }
1660
Brian Andersond0010582017-03-07 13:20:31 -08001661 setCompositorTimingSnapped(
1662 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1663}
1664
1665void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1666 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001667 // Integer division and modulo round toward 0 not -inf, so we need to
1668 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001669 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001670 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1671 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1672
Brian Andersond0010582017-03-07 13:20:31 -08001673 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1674 if (idealLatency <= 0) {
1675 idealLatency = vsyncInterval;
1676 }
1677
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001678 // Snap the latency to a value that removes scheduling jitter from the
1679 // composition and present times, which often have >1ms of jitter.
1680 // Reducing jitter is important if an app attempts to extrapolate
1681 // something (such as user input) to an accurate diasplay time.
1682 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1683 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001684 nsecs_t bias = vsyncInterval / 2;
1685 int64_t extraVsyncs =
1686 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1687 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1688 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001689
David Sodman99974d22017-11-28 12:04:33 -08001690 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1691 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1692 getBE().mCompositorTiming.interval = vsyncInterval;
1693 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001694}
1695
1696void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001697{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001698 ATRACE_CALL();
1699 ALOGV("postComposition");
1700
Brian Anderson3546a3f2016-07-14 11:51:14 -07001701 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001702 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001703 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001704 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001705 }
1706
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001707 // |mStateLock| not needed as we are on the main thread
1708 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001709
David Sodman73beded2017-11-15 11:56:06 -08001710 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001711 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001712 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001713 glCompositionDoneFenceTime =
1714 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001715 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001716 } else {
1717 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1718 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001719
David Sodman73beded2017-11-15 11:56:06 -08001720 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001721 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001722 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001723 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001724
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001725 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1726 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1727
1728 // We use the refreshStartTime which might be sampled a little later than
1729 // when we started doing work for this frame, but that should be okay
1730 // since updateCompositorTiming has snapping logic.
1731 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001732 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001733 CompositorTiming compositorTiming;
1734 {
David Sodman99974d22017-11-28 12:04:33 -08001735 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1736 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001737 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001738
Robert Carr2047fae2016-11-28 14:09:09 -08001739 mDrawingState.traverseInZOrder([&](Layer* layer) {
1740 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001741 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001742 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001743 recordBufferingStats(layer->getName().string(),
1744 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001745 }
Robert Carr2047fae2016-11-28 14:09:09 -08001746 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001747
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001748 if (presentFenceTime->isValid()) {
1749 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001750 enableHardwareVsync();
1751 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001752 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001753 }
1754 }
1755
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001756 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001757 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001758 enableHardwareVsync();
1759 }
1760 }
1761
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001762 if (mAnimCompositionPending) {
1763 mAnimCompositionPending = false;
1764
Brian Anderson4e606e32017-03-16 15:34:57 -07001765 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001766 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001767 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001768 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001769 // The HWC doesn't support present fences, so use the refresh
1770 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001771 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001772 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001773 mAnimFrameTracker.setActualPresentTime(presentTime);
1774 }
1775 mAnimFrameTracker.advanceFrame();
1776 }
Dan Stozab90cf072015-03-05 11:05:59 -08001777
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001778 mTimeStats.incrementTotalFrames();
1779 if (mHadClientComposition) {
1780 mTimeStats.incrementClientCompositionFrames();
1781 }
1782
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001783 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1784 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001785 return;
1786 }
1787
1788 nsecs_t currentTime = systemTime();
1789 if (mHasPoweredOff) {
1790 mHasPoweredOff = false;
1791 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001792 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001793 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001794 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1795 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001796 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001797 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001798 }
David Sodman4a36e932017-11-07 14:29:47 -08001799 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001800 }
David Sodman4a36e932017-11-07 14:29:47 -08001801 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001802}
1803
1804void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001805 ATRACE_CALL();
1806 ALOGV("rebuildLayerStacks");
1807
Mathias Agopiancd60f992012-08-16 16:28:27 -07001808 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001809 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001810 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001811 mVisibleRegionsDirty = false;
1812 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001813
Jeff Sharkey76488112017-02-27 14:15:18 -07001814 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1815 Region opaqueRegion;
1816 Region dirtyRegion;
1817 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001818 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001819 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1820 const Transform& tr(displayDevice->getTransform());
1821 const Rect bounds(displayDevice->getBounds());
1822 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001823 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001824
Jeff Sharkey76488112017-02-27 14:15:18 -07001825 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001826 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001827 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1828 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001829 Region drawRegion(tr.transform(
1830 layer->visibleNonTransparentRegion));
1831 drawRegion.andSelf(bounds);
1832 if (!drawRegion.isEmpty()) {
1833 layersSortedByZ.add(layer);
1834 } else {
1835 // Clear out the HWC layer if this layer was
1836 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001837 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001838 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001839 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001840 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001841 // WM changes displayDevice->layerStack upon sleep/awake.
1842 // Here we make sure we delete the HWC layers even if
1843 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001844 hwcLayerDestroyed = layer->destroyHwcLayer(
1845 displayDevice->getHwcDisplayId());
1846 }
1847
1848 // If a layer is not going to get a release fence because
1849 // it is invisible, but it is also going to release its
1850 // old buffer, add it to the list of layers needing
1851 // fences.
1852 if (hwcLayerDestroyed) {
1853 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1854 mLayersWithQueuedFrames.cend(), layer);
1855 if (found != mLayersWithQueuedFrames.cend()) {
1856 layersNeedingFences.add(layer);
1857 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001858 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001859 });
1860 }
1861 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001862 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001863 displayDevice->undefinedRegion.set(bounds);
1864 displayDevice->undefinedRegion.subtractSelf(
1865 tr.transform(opaqueRegion));
1866 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001867 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001868 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001869}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001870
Romain Guy0147a172017-06-01 13:53:56 -07001871mat4 SurfaceFlinger::computeSaturationMatrix() const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001872 if (mGlobalSaturationFactor == 1.0f) {
Romain Guy0147a172017-06-01 13:53:56 -07001873 return mat4();
1874 }
1875
1876 // Rec.709 luma coefficients
1877 float3 luminance{0.213f, 0.715f, 0.072f};
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001878 luminance *= 1.0f - mGlobalSaturationFactor;
Romain Guy0147a172017-06-01 13:53:56 -07001879 return mat4(
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001880 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
1881 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
1882 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
Romain Guy0147a172017-06-01 13:53:56 -07001883 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1884 );
1885}
1886
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001887// Returns a dataspace that fits all visible layers. The returned dataspace
1888// can only be one of
1889//
1890// - Dataspace::V0_SRGB
1891// - Dataspace::DISPLAY_P3
1892// - Dataspace::V0_SCRGB_LINEAR
1893// TODO(b/73825729) Add BT2020 data space.
1894ui::Dataspace SurfaceFlinger::getBestDataspace(
1895 const sp<const DisplayDevice>& displayDevice) const {
1896 Dataspace bestDataspace = Dataspace::V0_SRGB;
1897 for (const auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1898 switch (layer->getDataSpace()) {
1899 case Dataspace::V0_SCRGB:
1900 case Dataspace::V0_SCRGB_LINEAR:
1901 // return immediately
1902 return Dataspace::V0_SCRGB_LINEAR;
Peiyong Linf59a7192018-04-25 11:19:31 -07001903 case Dataspace::DISPLAY_P3:
1904 bestDataspace = Dataspace::DISPLAY_P3;
1905 break;
1906 // Historically, HDR dataspaces are ignored by SurfaceFlinger. But
1907 // since SurfaceFlinger simulates HDR support now, it should honor
1908 // them unless there is also native support.
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001909 case Dataspace::BT2020_PQ:
1910 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin62665892018-04-16 11:07:44 -07001911 if (!displayDevice->hasHDR10Support()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001912 return Dataspace::V0_SCRGB_LINEAR;
1913 }
1914 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001915 case Dataspace::BT2020_HLG:
1916 case Dataspace::BT2020_ITU_HLG:
1917 if (!displayDevice->hasHLGSupport()) {
1918 return Dataspace::V0_SCRGB_LINEAR;
1919 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001920 break;
1921 default:
1922 break;
1923 }
Romain Guy54f154a2017-10-24 21:40:32 +01001924 }
1925
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001926 return bestDataspace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001927}
1928
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001929// Pick the ColorMode / Dataspace for the display device.
1930// TODO(b/73825729) Add BT2020 color mode.
1931void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& displayDevice,
1932 ColorMode* outMode, Dataspace* outDataSpace) const {
1933 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1934 *outMode = ColorMode::NATIVE;
1935 *outDataSpace = Dataspace::UNKNOWN;
1936 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001937 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001938
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001939 switch (getBestDataspace(displayDevice)) {
1940 case Dataspace::DISPLAY_P3:
1941 case Dataspace::V0_SCRGB_LINEAR:
1942 *outMode = ColorMode::DISPLAY_P3;
1943 *outDataSpace = Dataspace::DISPLAY_P3;
1944 break;
1945 default:
1946 *outMode = ColorMode::SRGB;
1947 *outDataSpace = Dataspace::V0_SRGB;
1948 break;
1949 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001950}
1951
Mathias Agopiancd60f992012-08-16 16:28:27 -07001952void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001953 ATRACE_CALL();
1954 ALOGV("setUpHWComposer");
1955
Jesse Hall028dc8f2013-08-20 16:35:32 -07001956 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Dan Stozac7a25ad2018-04-12 11:45:09 -07001957 bool dirty = !mDisplays[dpy]->getDirtyRegion(mRepaintEverything).isEmpty();
Jesse Hallb7a05492014-08-14 15:45:06 -07001958 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1959 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1960
1961 // If nothing has changed (!dirty), don't recompose.
1962 // If something changed, but we don't currently have any visible layers,
1963 // and didn't when we last did a composition, then skip it this time.
1964 // The second rule does two things:
1965 // - When all layers are removed from a display, we'll emit one black
1966 // frame, then nothing more until we get new layers.
1967 // - When a display is created with a private layer stack, we won't
1968 // emit any black frames until a layer is added to the layer stack.
1969 bool mustRecompose = dirty && !(empty && wasEmpty);
1970
1971 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1972 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1973 mustRecompose ? "doing" : "skipping",
1974 dirty ? "+" : "-",
1975 empty ? "+" : "-",
1976 wasEmpty ? "+" : "-");
1977
Dan Stoza71433162014-02-04 16:22:36 -08001978 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001979
1980 if (mustRecompose) {
1981 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1982 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001983 }
1984
Dan Stoza9e56aa02015-11-02 13:00:03 -08001985 // build the h/w work list
1986 if (CC_UNLIKELY(mGeometryInvalid)) {
1987 mGeometryInvalid = false;
1988 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1989 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1990 const auto hwcId = displayDevice->getHwcDisplayId();
1991 if (hwcId >= 0) {
1992 const Vector<sp<Layer>>& currentLayers(
1993 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001994 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001995 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001996 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07001997 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001998 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001999 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07002000 }
2001 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07002002
Robert Carrae060832016-11-28 10:51:00 -08002003 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002004 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002005 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07002006 }
2007 }
2008 }
2009 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002010 }
Riley Andrews03414a12014-07-01 14:22:59 -07002011
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002012
Romain Guy0147a172017-06-01 13:53:56 -07002013 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002014
Dan Stoza9e56aa02015-11-02 13:00:03 -08002015 // Set the per-frame data
2016 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2017 auto& displayDevice = mDisplays[displayId];
2018 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002019
Dan Stoza9e56aa02015-11-02 13:00:03 -08002020 if (hwcId < 0) {
2021 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07002022 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002023 if (colorMatrix != mPreviousColorMatrix) {
Yiwei Zhang7c64f172018-03-07 14:52:28 -08002024 displayDevice->setColorTransform(colorMatrix);
David Sodman105b7dc2017-11-04 20:28:14 -07002025 status_t result = getBE().mHwc->setColorTransform(hwcId, colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002026 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
2027 "display %zd: %d", displayId, result);
2028 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002029 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002030 if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2031 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Peiyong Lin62665892018-04-16 11:07:44 -07002032 !displayDevice->hasHDR10Support()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002033 layer->forceClientComposition(hwcId);
2034 }
Peiyong Linf59a7192018-04-25 11:19:31 -07002035 if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
2036 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
2037 !displayDevice->hasHLGSupport()) {
2038 layer->forceClientComposition(hwcId);
2039 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002040
chaviwc9232ed2017-11-14 15:31:15 -08002041 if (layer->getForceClientComposition(hwcId)) {
2042 ALOGV("[%s] Requesting Client composition", layer->getName().string());
2043 layer->setCompositionType(hwcId, HWC2::Composition::Client);
2044 continue;
2045 }
2046
Dan Stoza9e56aa02015-11-02 13:00:03 -08002047 layer->setPerFrameData(displayDevice);
2048 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002049
2050 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002051 ColorMode colorMode;
2052 Dataspace dataSpace;
2053 pickColorMode(displayDevice, &colorMode, &dataSpace);
2054 setActiveColorModeInternal(displayDevice, colorMode, dataSpace);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002055 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002056 }
2057
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002058 mPreviousColorMatrix = colorMatrix;
2059
Dan Stoza9e56aa02015-11-02 13:00:03 -08002060 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002061 auto& displayDevice = mDisplays[displayId];
2062 if (!displayDevice->isDisplayOn()) {
2063 continue;
2064 }
2065
David Sodman105b7dc2017-11-04 20:28:14 -07002066 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002067 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2068 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002069 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002070}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002071
Mathias Agopiancd60f992012-08-16 16:28:27 -07002072void SurfaceFlinger::doComposition() {
2073 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002074 ALOGV("doComposition");
2075
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002076 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002077 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002078 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002079 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002080 // transform the dirty region into this screen's coordinate space
2081 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002082
2083 // repaint the framebuffer (if needed)
2084 doDisplayComposition(hw, dirtyRegion);
2085
Mathias Agopiancd60f992012-08-16 16:28:27 -07002086 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002087 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002088 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002089 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002090 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002091}
2092
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002093void SurfaceFlinger::postFramebuffer()
2094{
Mathias Agopian841cde52012-03-01 15:44:37 -08002095 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002096 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002097
Mathias Agopiana44b0412011-10-16 18:46:35 -07002098 const nsecs_t now = systemTime();
2099 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002100
Dan Stoza9e56aa02015-11-02 13:00:03 -08002101 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2102 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002103 if (!displayDevice->isDisplayOn()) {
2104 continue;
2105 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002106 const auto hwcId = displayDevice->getHwcDisplayId();
2107 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002108 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002109 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002110 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002111 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002112 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002113 // The layer buffer from the previous frame (if any) is released
2114 // by HWC only when the release fence from this frame (if any) is
2115 // signaled. Always get the release fence from HWC first.
2116 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002117 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002118
2119 // If the layer was client composited in the previous frame, we
2120 // need to merge with the previous client target acquire fence.
2121 // Since we do not track that, always merge with the current
2122 // client target acquire fence when it is available, even though
2123 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002124 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002125 releaseFence = Fence::merge("LayerRelease", releaseFence,
2126 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002127 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002128
Dan Stoza9e56aa02015-11-02 13:00:03 -08002129 layer->onLayerDisplayed(releaseFence);
2130 }
Chia-I Wu83806892017-11-16 10:50:20 -08002131
2132 // We've got a list of layers needing fences, that are disjoint with
2133 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2134 // supply them with the present fence.
2135 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002136 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002137 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2138 layer->onLayerDisplayed(presentFence);
2139 }
2140 }
2141
Dan Stoza9e56aa02015-11-02 13:00:03 -08002142 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002143 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002144 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002145 }
2146
Mathias Agopiana44b0412011-10-16 18:46:35 -07002147 mLastSwapBufferTime = systemTime() - now;
2148 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002149
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002150 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002151 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2152 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2153 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2154 logFrameStats();
2155 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002156 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002157}
2158
Mathias Agopian87baae12012-07-31 12:38:26 -07002159void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002160{
Mathias Agopian841cde52012-03-01 15:44:37 -08002161 ATRACE_CALL();
2162
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002163 // here we keep a copy of the drawing state (that is the state that's
2164 // going to be overwritten by handleTransactionLocked()) outside of
2165 // mStateLock so that the side-effects of the State assignment
2166 // don't happen with mStateLock held (which can cause deadlocks).
2167 State drawingState(mDrawingState);
2168
Mathias Agopianca4d3602011-05-19 15:38:14 -07002169 Mutex::Autolock _l(mStateLock);
2170 const nsecs_t now = systemTime();
2171 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002172
Mathias Agopianca4d3602011-05-19 15:38:14 -07002173 // Here we're guaranteed that some transaction flags are set
2174 // so we can call handleTransactionLocked() unconditionally.
2175 // We call getTransactionFlags(), which will also clear the flags,
2176 // with mStateLock held to guarantee that mCurrentState won't change
2177 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002178
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002179 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002180 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002181 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002182
Mathias Agopianca4d3602011-05-19 15:38:14 -07002183 mLastTransactionTime = systemTime() - now;
2184 mDebugInTransaction = 0;
2185 invalidateHwcGeometry();
2186 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002187}
2188
Lloyd Pique715a2c12017-12-14 17:18:08 -08002189DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique09594832018-01-22 17:48:03 -08002190 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002191 // Figure out whether the event is for the primary display or an
2192 // external display by matching the Hwc display id against one for a
2193 // connected display. If we did not find a match, we then check what
2194 // displays are not already connected to determine the type. If we don't
2195 // have a connected primary display, we assume the new display is meant to
2196 // be the primary display, and then if we don't have an external display,
2197 // we assume it is that.
2198 const auto primaryDisplayId =
2199 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2200 const auto externalDisplayId =
2201 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2202 if (primaryDisplayId && primaryDisplayId == display) {
2203 return DisplayDevice::DISPLAY_PRIMARY;
2204 } else if (externalDisplayId && externalDisplayId == display) {
2205 return DisplayDevice::DISPLAY_EXTERNAL;
2206 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2207 return DisplayDevice::DISPLAY_PRIMARY;
2208 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2209 return DisplayDevice::DISPLAY_EXTERNAL;
2210 }
2211
2212 return DisplayDevice::DISPLAY_ID_INVALID;
2213}
2214
Lloyd Piqueba04e622017-12-14 17:11:26 -08002215void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2216 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002217 auto displayType = determineDisplayType(event.display, event.connection);
2218 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2219 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2220 continue;
2221 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002222
2223 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2224 ALOGE("External displays are not supported by the vr hardware composer.");
2225 continue;
2226 }
2227
Lloyd Pique715a2c12017-12-14 17:18:08 -08002228 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002229
2230 if (event.connection == HWC2::Connection::Connected) {
Steven Thomas3bed0522018-03-20 15:40:48 -07002231 if (!mBuiltinDisplays[displayType].get()) {
2232 ALOGV("Creating built in display %d", displayType);
2233 mBuiltinDisplays[displayType] = new BBinder();
2234 // All non-virtual displays are currently considered secure.
2235 DisplayDeviceState info(displayType, true);
2236 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2237 "Built-in Screen" : "External Screen";
2238 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
Lloyd Pique4d234852018-01-22 17:21:36 -08002239 mInterceptor->saveDisplayCreation(info);
Steven Thomas3bed0522018-03-20 15:40:48 -07002240 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002241 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002242 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002243
Lloyd Piquefcd86612017-12-14 17:15:36 -08002244 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2245 if (idx >= 0) {
2246 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Lloyd Pique4d234852018-01-22 17:21:36 -08002247 mInterceptor->saveDisplayDeletion(info.displayId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002248 mCurrentState.displays.removeItemsAt(idx);
2249 }
2250 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002251 }
2252
2253 processDisplayChangesLocked();
2254 }
2255
2256 mPendingHotplugEvents.clear();
2257}
2258
Lloyd Pique09594832018-01-22 17:48:03 -08002259sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2260 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2261 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002262 bool hasWideColorGamut = false;
Lloyd Pique09594832018-01-22 17:48:03 -08002263 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002264 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Lloyd Pique09594832018-01-22 17:48:03 -08002265 for (ColorMode colorMode : modes) {
2266 switch (colorMode) {
2267 case ColorMode::DISPLAY_P3:
2268 case ColorMode::ADOBE_RGB:
2269 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002270 hasWideColorGamut = true;
Lloyd Pique09594832018-01-22 17:48:03 -08002271 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002272 // TODO(lpy) Handle BT2020, BT2100_PQ and BT2100_HLG properly.
Lloyd Pique09594832018-01-22 17:48:03 -08002273 default:
2274 break;
2275 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002276
2277 std::vector<RenderIntent> renderIntents = getHwComposer().getRenderIntents(hwcId,
2278 colorMode);
2279 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2280 for (auto intent : renderIntents) {
2281 if (intent == RenderIntent::ENHANCE) {
2282 mBuiltinDisplaySupportsEnhance = true;
2283 break;
2284 }
2285 }
2286 }
Lloyd Pique09594832018-01-22 17:48:03 -08002287 }
2288 }
2289
Peiyong Lin62665892018-04-16 11:07:44 -07002290 HdrCapabilities hdrCapabilities;
2291 getHwComposer().getHdrCapabilities(hwcId, &hdrCapabilities);
Lloyd Pique09594832018-01-22 17:48:03 -08002292
2293 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2294 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2295
2296 /*
2297 * Create our display's surface
2298 */
2299 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2300 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
2301 renderSurface->setAsync(state.type >= DisplayDevice::DISPLAY_VIRTUAL);
2302 renderSurface->setNativeWindow(nativeWindow.get());
2303 const int displayWidth = renderSurface->queryWidth();
2304 const int displayHeight = renderSurface->queryHeight();
2305
2306 // Make sure that composition can never be stalled by a virtual display
2307 // consumer that isn't processing buffers fast enough. We have to do this
2308 // in two places:
2309 // * Here, in case the display is composed entirely by HWC.
2310 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2311 // window's swap interval in eglMakeCurrent, so they'll override the
2312 // interval we set here.
2313 if (state.type >= DisplayDevice::DISPLAY_VIRTUAL) {
2314 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2315 }
2316
2317 // virtual displays are always considered enabled
2318 auto initialPowerMode = (state.type >= DisplayDevice::DISPLAY_VIRTUAL) ? HWC_POWER_MODE_NORMAL
2319 : HWC_POWER_MODE_OFF;
2320
2321 sp<DisplayDevice> hw =
2322 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2323 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
Peiyong Lin2c327ac2018-04-19 22:06:34 -07002324 hasWideColorGamut, hdrCapabilities,
2325 getHwComposer().getSupportedPerFrameMetadata(hwcId),
2326 initialPowerMode);
Lloyd Pique09594832018-01-22 17:48:03 -08002327
2328 if (maxFrameBufferAcquiredBuffers >= 3) {
2329 nativeWindowSurface->preallocateBuffers();
2330 }
2331
2332 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002333 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2334 if (hasWideColorGamut) {
Lloyd Pique09594832018-01-22 17:48:03 -08002335 defaultColorMode = ColorMode::SRGB;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002336 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique09594832018-01-22 17:48:03 -08002337 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002338 setActiveColorModeInternal(hw, defaultColorMode, defaultDataSpace);
Lloyd Pique09594832018-01-22 17:48:03 -08002339 hw->setLayerStack(state.layerStack);
2340 hw->setProjection(state.orientation, state.viewport, state.frame);
2341 hw->setDisplayName(state.displayName);
2342
2343 return hw;
2344}
2345
Lloyd Pique347200f2017-12-14 17:00:15 -08002346void SurfaceFlinger::processDisplayChangesLocked() {
2347 // here we take advantage of Vector's copy-on-write semantics to
2348 // improve performance by skipping the transaction entirely when
2349 // know that the lists are identical
2350 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2351 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2352 if (!curr.isIdenticalTo(draw)) {
2353 mVisibleRegionsDirty = true;
2354 const size_t cc = curr.size();
2355 size_t dc = draw.size();
2356
2357 // find the displays that were removed
2358 // (ie: in drawing state but not in current state)
2359 // also handle displays that changed
2360 // (ie: displays that are in both lists)
2361 for (size_t i = 0; i < dc;) {
2362 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2363 if (j < 0) {
2364 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002365 // Call makeCurrent() on the primary display so we can
2366 // be sure that nothing associated with this display
2367 // is current.
2368 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2369 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2370 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2371 if (hw != nullptr) hw->disconnect(getHwComposer());
2372 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2373 mEventThread->onHotplugReceived(draw[i].type, false);
2374 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002375 } else {
2376 // this display is in both lists. see if something changed.
2377 const DisplayDeviceState& state(curr[j]);
2378 const wp<IBinder>& display(curr.keyAt(j));
2379 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2380 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2381 if (state_binder != draw_binder) {
2382 // changing the surface is like destroying and
2383 // recreating the DisplayDevice, so we just remove it
2384 // from the drawing state, so that it get re-added
2385 // below.
2386 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2387 if (hw != nullptr) hw->disconnect(getHwComposer());
2388 mDisplays.removeItem(display);
2389 mDrawingState.displays.removeItemsAt(i);
2390 dc--;
2391 // at this point we must loop to the next item
2392 continue;
2393 }
2394
2395 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2396 if (disp != nullptr) {
2397 if (state.layerStack != draw[i].layerStack) {
2398 disp->setLayerStack(state.layerStack);
2399 }
2400 if ((state.orientation != draw[i].orientation) ||
2401 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2402 disp->setProjection(state.orientation, state.viewport, state.frame);
2403 }
2404 if (state.width != draw[i].width || state.height != draw[i].height) {
2405 disp->setDisplaySize(state.width, state.height);
2406 }
2407 }
2408 }
2409 ++i;
2410 }
2411
2412 // find displays that were added
2413 // (ie: in current state but not in drawing state)
2414 for (size_t i = 0; i < cc; i++) {
2415 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2416 const DisplayDeviceState& state(curr[i]);
2417
2418 sp<DisplaySurface> dispSurface;
2419 sp<IGraphicBufferProducer> producer;
2420 sp<IGraphicBufferProducer> bqProducer;
2421 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002422 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002423
2424 int32_t hwcId = -1;
2425 if (state.isVirtualDisplay()) {
2426 // Virtual displays without a surface are dormant:
2427 // they have external state (layer stack, projection,
2428 // etc.) but no internal state (i.e. a DisplayDevice).
2429 if (state.surface != nullptr) {
2430 // Allow VR composer to use virtual displays.
2431 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2432 int width = 0;
2433 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2434 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2435 int height = 0;
2436 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2437 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2438 int intFormat = 0;
2439 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2440 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002441 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002442
2443 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2444 }
2445
2446 // TODO: Plumb requested format back up to consumer
2447
2448 sp<VirtualDisplaySurface> vds =
2449 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2450 bqProducer, bqConsumer,
2451 state.displayName);
2452
2453 dispSurface = vds;
2454 producer = vds;
2455 }
2456 } else {
2457 ALOGE_IF(state.surface != nullptr,
2458 "adding a supported display, but rendering "
2459 "surface is provided (%p), ignoring it",
2460 state.surface.get());
2461
2462 hwcId = state.type;
2463 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2464 producer = bqProducer;
2465 }
2466
2467 const wp<IBinder>& display(curr.keyAt(i));
2468 if (dispSurface != nullptr) {
Lloyd Pique09594832018-01-22 17:48:03 -08002469 mDisplays.add(display,
2470 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2471 producer));
Lloyd Pique347200f2017-12-14 17:00:15 -08002472 if (!state.isVirtualDisplay()) {
2473 mEventThread->onHotplugReceived(state.type, true);
2474 }
2475 }
2476 }
2477 }
2478 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002479
2480 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002481}
2482
Mathias Agopian87baae12012-07-31 12:38:26 -07002483void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002484{
Dan Stoza7dde5992015-05-22 09:51:44 -07002485 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002486 mCurrentState.traverseInZOrder([](Layer* layer) {
2487 layer->notifyAvailableFrames();
2488 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002489
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002490 /*
2491 * Traversal of the children
2492 * (perform the transaction for each of them if needed)
2493 */
2494
Mathias Agopian3559b072012-08-15 13:46:03 -07002495 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002496 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002497 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002498 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002499
2500 const uint32_t flags = layer->doTransaction(0);
2501 if (flags & Layer::eVisibleRegion)
2502 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002503 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002504 }
2505
2506 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002507 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002508 */
2509
Mathias Agopiane57f2922012-08-09 16:29:12 -07002510 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002511 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002512 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002513 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002514
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002515 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002516 // The transform hint might have changed for some layers
2517 // (either because a display has changed, or because a layer
2518 // as changed).
2519 //
2520 // Walk through all the layers in currentLayers,
2521 // and update their transform hint.
2522 //
2523 // If a layer is visible only on a single display, then that
2524 // display is used to calculate the hint, otherwise we use the
2525 // default display.
2526 //
2527 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2528 // the hint is set before we acquire a buffer from the surface texture.
2529 //
2530 // NOTE: layer transactions have taken place already, so we use their
2531 // drawing state. However, SurfaceFlinger's own transaction has not
2532 // happened yet, so we must use the current state layer list
2533 // (soon to become the drawing state list).
2534 //
2535 sp<const DisplayDevice> disp;
2536 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002537 bool first = true;
2538 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002539 // NOTE: we rely on the fact that layers are sorted by
2540 // layerStack first (so we don't have to traverse the list
2541 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002542 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002543 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002544 currentlayerStack = layerStack;
2545 // figure out if this layerstack is mirrored
2546 // (more than one display) if so, pick the default display,
2547 // if not, pick the only display it's on.
2548 disp.clear();
2549 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2550 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002551 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002552 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002553 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002554 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002555 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002556 break;
2557 }
2558 }
2559 }
2560 }
Chet Haase91d25932013-04-11 15:24:55 -07002561
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002562 if (disp == nullptr) {
2563 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2564 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002565
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002566 // could be null when this layer is using a layerStack
2567 // that is not visible on any display. Also can occur at
2568 // screen off/on times.
2569 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002570 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002571
2572 // disp can be null if there is no display available at all to get
2573 // the transform hint from.
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002574 if (disp != nullptr) {
2575 layer->updateTransformHint(disp);
2576 }
Robert Carr2047fae2016-11-28 14:09:09 -08002577
2578 first = false;
2579 });
Mathias Agopian84300952012-11-21 16:02:13 -08002580 }
2581
2582
Mathias Agopian3559b072012-08-15 13:46:03 -07002583 /*
2584 * Perform our own transaction if needed
2585 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002586
2587 if (mLayersAdded) {
2588 mLayersAdded = false;
2589 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002590 mVisibleRegionsDirty = true;
2591 }
2592
2593 // some layers might have been removed, so
2594 // we need to update the regions they're exposing.
2595 if (mLayersRemoved) {
2596 mLayersRemoved = false;
2597 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002598 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002599 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002600 // this layer is not visible anymore
2601 // TODO: we could traverse the tree from front to back and
2602 // compute the actual visible region
2603 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002604 Region visibleReg;
2605 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002606 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002607 }
Robert Carr2047fae2016-11-28 14:09:09 -08002608 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002609 }
2610
2611 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002612
2613 updateCursorAsync();
2614}
2615
2616void SurfaceFlinger::updateCursorAsync()
2617{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002618 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2619 auto& displayDevice = mDisplays[displayId];
2620 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002621 continue;
2622 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002623
2624 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2625 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002626 }
2627 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002628}
2629
2630void SurfaceFlinger::commitTransaction()
2631{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002632 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002633 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002634 for (const auto& l : mLayersPendingRemoval) {
2635 recordBufferingStats(l->getName().string(),
2636 l->getOccupancyHistory(true));
2637 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002638 }
2639 mLayersPendingRemoval.clear();
2640 }
2641
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002642 // If this transaction is part of a window animation then the next frame
2643 // we composite should be considered an animation as well.
2644 mAnimCompositionPending = mAnimTransactionPending;
2645
Mathias Agopian4fec8732012-06-29 14:12:52 -07002646 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002647 mDrawingState.traverseInZOrder([](Layer* layer) {
2648 layer->commitChildList();
2649 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002650 mTransactionPending = false;
2651 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002652 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002653}
2654
Chia-I Wuab0c3192017-08-01 11:29:00 -07002655void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002656 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002657{
Mathias Agopian841cde52012-03-01 15:44:37 -08002658 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002659 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002660
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002661 Region aboveOpaqueLayers;
2662 Region aboveCoveredLayers;
2663 Region dirty;
2664
Mathias Agopian87baae12012-07-31 12:38:26 -07002665 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002666
Robert Carr2047fae2016-11-28 14:09:09 -08002667 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002668 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002669 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002670
Jesse Hall01e29052013-02-19 16:13:35 -08002671 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002672 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002673 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002674
Mathias Agopianab028732010-03-16 16:41:46 -07002675 /*
2676 * opaqueRegion: area of a surface that is fully opaque.
2677 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002678 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002679
2680 /*
2681 * visibleRegion: area of a surface that is visible on screen
2682 * and not fully transparent. This is essentially the layer's
2683 * footprint minus the opaque regions above it.
2684 * Areas covered by a translucent surface are considered visible.
2685 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002686 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002687
2688 /*
2689 * coveredRegion: area of a surface that is covered by all
2690 * visible regions above it (which includes the translucent areas).
2691 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002692 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002693
Jesse Halla8026d22012-09-25 13:25:04 -07002694 /*
2695 * transparentRegion: area of a surface that is hinted to be completely
2696 * transparent. This is only used to tell when the layer has no visible
2697 * non-transparent regions and can be removed from the layer list. It
2698 * does not affect the visibleRegion of this layer or any layers
2699 * beneath it. The hint may not be correct if apps don't respect the
2700 * SurfaceView restrictions (which, sadly, some don't).
2701 */
2702 Region transparentRegion;
2703
Mathias Agopianab028732010-03-16 16:41:46 -07002704
2705 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002706 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002707 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002708 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002709 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002710 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002711 if (!visibleRegion.isEmpty()) {
2712 // Remove the transparent area from the visible region
2713 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002714 if (tr.preserveRects()) {
2715 // transform the transparent region
2716 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002717 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002718 // transformation too complex, can't do the
2719 // transparent region optimization.
2720 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002721 }
Mathias Agopianab028732010-03-16 16:41:46 -07002722 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002723
Mathias Agopianab028732010-03-16 16:41:46 -07002724 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002725 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002726 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002727 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2728 // the opaque region is the layer's footprint
2729 opaqueRegion = visibleRegion;
2730 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002731 }
2732 }
2733
Robert Carre5f4f692018-01-12 13:12:28 -08002734 if (visibleRegion.isEmpty()) {
2735 layer->clearVisibilityRegions();
2736 return;
2737 }
2738
Mathias Agopianab028732010-03-16 16:41:46 -07002739 // Clip the covered region to the visible region
2740 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2741
2742 // Update aboveCoveredLayers for next (lower) layer
2743 aboveCoveredLayers.orSelf(visibleRegion);
2744
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002745 // subtract the opaque region covered by the layers above us
2746 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002747
2748 // compute this layer's dirty region
2749 if (layer->contentDirty) {
2750 // we need to invalidate the whole region
2751 dirty = visibleRegion;
2752 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002753 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002754 layer->contentDirty = false;
2755 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002756 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002757 * the exposed region consists of two components:
2758 * 1) what's VISIBLE now and was COVERED before
2759 * 2) what's EXPOSED now less what was EXPOSED before
2760 *
2761 * note that (1) is conservative, we start with the whole
2762 * visible region but only keep what used to be covered by
2763 * something -- which mean it may have been exposed.
2764 *
2765 * (2) handles areas that were not covered by anything but got
2766 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002767 */
Mathias Agopianab028732010-03-16 16:41:46 -07002768 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002769 const Region oldVisibleRegion = layer->visibleRegion;
2770 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002771 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2772 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002773 }
2774 dirty.subtractSelf(aboveOpaqueLayers);
2775
2776 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002777 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002778
Mathias Agopianab028732010-03-16 16:41:46 -07002779 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002780 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002781
Jesse Halla8026d22012-09-25 13:25:04 -07002782 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002783 layer->setVisibleRegion(visibleRegion);
2784 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002785 layer->setVisibleNonTransparentRegion(
2786 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002787 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002788
Mathias Agopian87baae12012-07-31 12:38:26 -07002789 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002790}
2791
Chia-I Wuab0c3192017-08-01 11:29:00 -07002792void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002793 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002794 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002795 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002796 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002797 }
2798 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002799}
2800
Dan Stoza6b9454d2014-11-07 16:00:59 -08002801bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002802{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002803 ALOGV("handlePageFlip");
2804
Brian Andersond6927fb2016-07-23 23:37:30 -07002805 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002806
Mathias Agopian4fec8732012-06-29 14:12:52 -07002807 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002808 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002809 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002810
2811 // Store the set of layers that need updates. This set must not change as
2812 // buffers are being latched, as this could result in a deadlock.
2813 // Example: Two producers share the same command stream and:
2814 // 1.) Layer 0 is latched
2815 // 2.) Layer 0 gets a new frame
2816 // 2.) Layer 1 gets a new frame
2817 // 3.) Layer 1 is latched.
2818 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2819 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002820 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002821 if (layer->hasQueuedFrame()) {
2822 frameQueued = true;
2823 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002824 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002825 } else {
2826 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002827 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002828 } else {
2829 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002830 }
Robert Carr2047fae2016-11-28 14:09:09 -08002831 });
2832
Dan Stoza9e56aa02015-11-02 13:00:03 -08002833 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002834 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002835 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002836 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002837 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002838 newDataLatched = true;
2839 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002840 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002841
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002842 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002843
2844 // If we will need to wake up at some time in the future to deal with a
2845 // queued frame that shouldn't be displayed during this vsync period, wake
2846 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002847 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002848 signalLayerUpdate();
2849 }
2850
2851 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002852 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002853}
2854
Mathias Agopianad456f92011-01-13 17:53:01 -08002855void SurfaceFlinger::invalidateHwcGeometry()
2856{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002857 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002858}
2859
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002860
Fabien Sanglard830b8472016-11-30 16:35:58 -08002861void SurfaceFlinger::doDisplayComposition(
2862 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002863 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002864{
Dan Stoza71433162014-02-04 16:22:36 -08002865 // We only need to actually compose the display if:
2866 // 1) It is being handled by hardware composer, which may need this to
2867 // keep its virtual display state machine in sync, or
2868 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002869 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002870 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002871 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002872 return;
2873 }
2874
Dan Stoza9e56aa02015-11-02 13:00:03 -08002875 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002876 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002877
2878 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002879 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002880}
2881
Chia-I Wub02087d2017-11-09 10:19:54 -08002882bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002883{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002884 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002885
Chia-I Wub02087d2017-11-09 10:19:54 -08002886 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002887 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002888 const auto hwcId = displayDevice->getHwcDisplayId();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002889 const bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
2890 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
2891 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2892 HWC2::Capability::SkipClientColorTransform);
2893 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002894
2895 mat4 oldColorMatrix;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002896 mat4 legacySrgbSaturationMatrix = mLegacySrgbSaturationMatrix;
2897 const bool applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002898 if (applyColorMatrix) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002899 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002900 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002901 legacySrgbSaturationMatrix = colorMatrix * legacySrgbSaturationMatrix;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002902 }
2903
Dan Stoza9e56aa02015-11-02 13:00:03 -08002904 if (hasClientComposition) {
2905 ALOGV("hasClientComposition");
2906
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002907 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002908 if (displayDevice->hasWideColorGamut()) {
2909 outputDataspace = displayDevice->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002910 }
2911 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002912 getBE().mRenderEngine->setDisplayMaxLuminance(
2913 displayDevice->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002914
Chia-I Wu7f402902017-11-09 12:51:10 -08002915 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002916 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002917 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002918 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002919
2920 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002921 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002922 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2923 }
2924 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002925 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002926
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002927 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002928 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002929 // when using overlays, we assume a fully transparent framebuffer
2930 // NOTE: we could reduce how much we need to clear, for instance
2931 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002932 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002933 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002934 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002935 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002936 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002937 // we're left with the letterbox region
2938 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002939 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002940
2941 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002942 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002943
Mathias Agopianb9494d52012-04-18 02:28:45 -07002944 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002945 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002946 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002947 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002948 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002949 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002950
Dan Stoza9e56aa02015-11-02 13:00:03 -08002951 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002952 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002953 // scissor on the main display. It should never be needed
2954 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002955 const Rect& bounds(displayDevice->getBounds());
2956 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002957 if (scissor != bounds) {
2958 // scissor doesn't match the screen's dimensions, so we
2959 // need to clear everything outside of it and enable
2960 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002961
Mathias Agopianf45c5102012-10-24 16:29:17 -07002962 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002963 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002964 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002965 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002966 }
2967 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002968 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002969
Mathias Agopian85d751c2012-08-29 16:59:24 -07002970 /*
2971 * and then, render the layers targeted at the framebuffer
2972 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002973
Dan Stoza9e56aa02015-11-02 13:00:03 -08002974 ALOGV("Rendering client layers");
2975 const Transform& displayTransform = displayDevice->getTransform();
2976 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002977 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002978 bool firstLayer = true;
2979 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002980 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002981 displayTransform.transform(layer->visibleRegion)));
2982 ALOGV("Layer: %s", layer->getName().string());
2983 ALOGV(" Composition type: %s",
2984 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002985 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002986 switch (layer->getCompositionType(hwcId)) {
2987 case HWC2::Composition::Cursor:
2988 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002989 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002990 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002991 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002992 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002993 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002994 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002995 // never clear the very first layer since we're
2996 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002997 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002998 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002999 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003000 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003001 case HWC2::Composition::Client: {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003002 // Only apply saturation matrix layer that is legacy SRGB dataspace
3003 // when auto color mode is on.
3004 bool restore = false;
3005 mat4 savedMatrix;
3006 if (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
3007 layer->isLegacySrgbDataSpace()) {
3008 savedMatrix =
3009 getRenderEngine().setupColorTransform(legacySrgbSaturationMatrix);
3010 restore = true;
3011 }
chaviwa76b2712017-09-20 12:02:26 -07003012 layer->draw(renderArea, clip);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003013 if (restore) {
3014 getRenderEngine().setupColorTransform(savedMatrix);
3015 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003016 break;
3017 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003018 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07003019 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003020 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003021 } else {
3022 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003023 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003024 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003025 }
3026 } else {
3027 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08003028 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08003029 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08003030 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07003031 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07003032 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07003033 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003034 }
3035 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003036
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003037 if (applyColorMatrix) {
3038 getRenderEngine().setupColorTransform(oldColorMatrix);
3039 }
3040
Mathias Agopianf45c5102012-10-24 16:29:17 -07003041 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003042 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003043 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003044}
3045
Fabien Sanglard830b8472016-11-30 16:35:58 -08003046void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
3047 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003048 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003049 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003050}
3051
Dan Stoza7d89d062015-04-30 13:29:25 -07003052status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003053 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003054 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003055 const sp<Layer>& lbc,
3056 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003057{
Dan Stoza7d89d062015-04-30 13:29:25 -07003058 // add this layer to the current state list
3059 {
3060 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003061 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003062 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3063 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003064 return NO_MEMORY;
3065 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003066 if (parent == nullptr) {
3067 mCurrentState.layersSortedByZ.add(lbc);
3068 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003069 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003070 ALOGE("addClientLayer called with a removed parent");
3071 return NAME_NOT_FOUND;
3072 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003073 parent->addChild(lbc);
3074 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003075
Dan Stoza101d8dc2018-02-27 15:42:25 -08003076 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
Dan Stoza0a0158c2018-03-16 13:38:54 -07003077 // TODO (b/74616334): Change this back to a fatal assert once the leak is fixed
3078 ALOGE_IF(mGraphicBufferProducerList.size() > mMaxGraphicBufferProducerListSize,
3079 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3080 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize,
3081 mNumLayers);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003082 mLayersAdded = true;
3083 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003084 }
3085
Mathias Agopian96f08192010-06-02 23:28:45 -07003086 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003087 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003088
Dan Stoza7d89d062015-04-30 13:29:25 -07003089 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003090}
3091
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003092status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003093 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003094 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3095}
Robert Carr7f9b8992017-03-10 11:08:39 -08003096
chaviwca27f252018-02-06 16:46:39 -08003097status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3098 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003099 if (layer->isPendingRemoval()) {
3100 return NO_ERROR;
3101 }
3102
Robert Carr1f0a16a2016-10-24 16:27:39 -07003103 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003104 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003105 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003106 if (topLevelOnly) {
3107 return NO_ERROR;
3108 }
3109
Chia-I Wu98f1c102017-05-30 14:54:08 -07003110 sp<Layer> ancestor = p;
3111 while (ancestor->getParent() != nullptr) {
3112 ancestor = ancestor->getParent();
3113 }
3114 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3115 ALOGE("removeLayer called with a layer whose parent has been removed");
3116 return NAME_NOT_FOUND;
3117 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003118
3119 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003120 } else {
3121 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003122 }
3123
Robert Carr136e2f62017-02-08 17:54:29 -08003124 // As a matter of normal operation, the LayerCleaner will produce a second
3125 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3126 // so we will succeed in promoting it, but it's already been removed
3127 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3128 // otherwise something has gone wrong and we are leaking the layer.
3129 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003130 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3131 layer->getName().string(),
3132 (p != nullptr) ? p->getName().string() : "no-parent");
3133 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003134 } else if (index < 0) {
3135 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003136 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003137
Chia-I Wuc6657022017-08-15 11:18:17 -07003138 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003139 mLayersPendingRemoval.add(layer);
3140 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003141 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003142 setTransactionFlags(eTransactionNeeded);
3143 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003144}
3145
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003146uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003147 return android_atomic_release_load(&mTransactionFlags);
3148}
3149
Mathias Agopian3f844832013-08-07 21:24:32 -07003150uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003151 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3152}
3153
Mathias Agopian3f844832013-08-07 21:24:32 -07003154uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza2713c302018-03-28 17:07:36 -07003155 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3156}
3157
3158uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3159 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003160 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza2713c302018-03-28 17:07:36 -07003161 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003162 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003163 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003164 }
3165 return old;
3166}
3167
chaviwca27f252018-02-06 16:46:39 -08003168bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3169 for (const ComposerState& state : states) {
3170 // Here we need to check that the interface we're given is indeed
3171 // one of our own. A malicious client could give us a nullptr
3172 // IInterface, or one of its own or even one of our own but a
3173 // different type. All these situations would cause us to crash.
3174 if (state.client == nullptr) {
3175 return true;
3176 }
3177
3178 sp<IBinder> binder = IInterface::asBinder(state.client);
3179 if (binder == nullptr) {
3180 return true;
3181 }
3182
3183 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3184 return true;
3185 }
3186 }
3187 return false;
3188}
3189
Mathias Agopian8b33f032012-07-24 20:43:54 -07003190void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003191 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003192 const Vector<DisplayState>& displays,
3193 uint32_t flags)
3194{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003195 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003196 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003197 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003198
chaviwca27f252018-02-06 16:46:39 -08003199 if (containsAnyInvalidClientState(states)) {
3200 return;
3201 }
3202
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003203 if (flags & eAnimation) {
3204 // For window updates that are part of an animation we must wait for
3205 // previous animation "frames" to be handled.
3206 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003207 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003208 if (CC_UNLIKELY(err != NO_ERROR)) {
3209 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003210 // caller after a few seconds.
3211 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3212 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003213 mAnimTransactionPending = false;
3214 break;
3215 }
3216 }
3217 }
3218
chaviwca27f252018-02-06 16:46:39 -08003219 for (const DisplayState& display : displays) {
3220 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003221 }
3222
chaviwca27f252018-02-06 16:46:39 -08003223 for (const ComposerState& state : states) {
3224 transactionFlags |= setClientStateLocked(state);
3225 }
3226
3227 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3228 // as destroyed should only occur after setting all other states. This is to allow for a
3229 // child re-parent to happen before marking its original parent as destroyed (which would
3230 // then mark the child as destroyed).
3231 for (const ComposerState& state : states) {
3232 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003233 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003234
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003235 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3236 // anyway. This can be used as a flush mechanism for previous async transactions.
3237 // Empty animation transaction can be used to simulate back-pressure, so also force a
3238 // transaction for empty animation transactions.
3239 if (transactionFlags == 0 &&
3240 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003241 transactionFlags = eTransactionNeeded;
3242 }
3243
Mathias Agopian386aa982011-11-07 21:58:03 -08003244 if (transactionFlags) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003245 if (mInterceptor->isEnabled()) {
3246 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003247 }
Irvel468051e2016-06-13 16:44:44 -07003248
Mathias Agopian386aa982011-11-07 21:58:03 -08003249 // this triggers the transaction
Dan Stoza2713c302018-03-28 17:07:36 -07003250 const auto start = (flags & eEarlyWakeup)
3251 ? VSyncModulator::TransactionStart::EARLY
3252 : VSyncModulator::TransactionStart::NORMAL;
3253 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003254
3255 // if this is a synchronous transaction, wait for it to take effect
3256 // before returning.
3257 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003258 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003259 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003260 if (flags & eAnimation) {
3261 mAnimTransactionPending = true;
3262 }
3263 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003264 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3265 if (CC_UNLIKELY(err != NO_ERROR)) {
3266 // just in case something goes wrong in SF, return to the
3267 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003268 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3269 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003270 break;
3271 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003272 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003273 }
3274}
3275
Mathias Agopiane57f2922012-08-09 16:29:12 -07003276uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3277{
Jesse Hall9a143922012-10-04 16:29:19 -07003278 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3279 if (dpyIdx < 0)
3280 return 0;
3281
Mathias Agopiane57f2922012-08-09 16:29:12 -07003282 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003283 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003284 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003285 const uint32_t what = s.what;
3286 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003287 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003288 disp.surface = s.surface;
3289 flags |= eDisplayTransactionNeeded;
3290 }
3291 }
3292 if (what & DisplayState::eLayerStackChanged) {
3293 if (disp.layerStack != s.layerStack) {
3294 disp.layerStack = s.layerStack;
3295 flags |= eDisplayTransactionNeeded;
3296 }
3297 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003298 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003299 if (disp.orientation != s.orientation) {
3300 disp.orientation = s.orientation;
3301 flags |= eDisplayTransactionNeeded;
3302 }
3303 if (disp.frame != s.frame) {
3304 disp.frame = s.frame;
3305 flags |= eDisplayTransactionNeeded;
3306 }
3307 if (disp.viewport != s.viewport) {
3308 disp.viewport = s.viewport;
3309 flags |= eDisplayTransactionNeeded;
3310 }
3311 }
Michael Lentine47e45402014-07-18 15:34:25 -07003312 if (what & DisplayState::eDisplaySizeChanged) {
3313 if (disp.width != s.width) {
3314 disp.width = s.width;
3315 flags |= eDisplayTransactionNeeded;
3316 }
3317 if (disp.height != s.height) {
3318 disp.height = s.height;
3319 flags |= eDisplayTransactionNeeded;
3320 }
3321 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003322 }
3323 return flags;
3324}
3325
chaviwca27f252018-02-06 16:46:39 -08003326uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3327 const layer_state_t& s = composerState.state;
3328 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3329
Mathias Agopian13127d82013-03-05 17:47:11 -08003330 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003331 if (layer == nullptr) {
3332 return 0;
3333 }
3334
3335 if (layer->isPendingRemoval()) {
3336 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3337 return 0;
3338 }
3339
3340 uint32_t flags = 0;
3341
3342 const uint32_t what = s.what;
3343 bool geometryAppliesWithResize =
3344 what & layer_state_t::eGeometryAppliesWithResize;
3345 if (what & layer_state_t::ePositionChanged) {
3346 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3347 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003348 }
chaviw8b3871a2017-11-01 17:41:01 -07003349 }
3350 if (what & layer_state_t::eLayerChanged) {
3351 // NOTE: index needs to be calculated before we update the state
3352 const auto& p = layer->getParent();
3353 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003354 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003355 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003356 mCurrentState.layersSortedByZ.removeAt(idx);
3357 mCurrentState.layersSortedByZ.add(layer);
3358 // we need traversal (state changed)
3359 // AND transaction (list changed)
3360 flags |= eTransactionNeeded|eTraversalNeeded;
3361 }
chaviw8b3871a2017-11-01 17:41:01 -07003362 } else {
3363 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003364 flags |= eTransactionNeeded|eTraversalNeeded;
3365 }
3366 }
chaviw8b3871a2017-11-01 17:41:01 -07003367 }
3368 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003369 // NOTE: index needs to be calculated before we update the state
3370 const auto& p = layer->getParent();
3371 if (p == nullptr) {
3372 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3373 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3374 mCurrentState.layersSortedByZ.removeAt(idx);
3375 mCurrentState.layersSortedByZ.add(layer);
3376 // we need traversal (state changed)
3377 // AND transaction (list changed)
3378 flags |= eTransactionNeeded|eTraversalNeeded;
3379 }
3380 } else {
3381 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3382 flags |= eTransactionNeeded|eTraversalNeeded;
3383 }
chaviw8b3871a2017-11-01 17:41:01 -07003384 }
3385 }
3386 if (what & layer_state_t::eSizeChanged) {
3387 if (layer->setSize(s.w, s.h)) {
3388 flags |= eTraversalNeeded;
3389 }
3390 }
3391 if (what & layer_state_t::eAlphaChanged) {
3392 if (layer->setAlpha(s.alpha))
3393 flags |= eTraversalNeeded;
3394 }
3395 if (what & layer_state_t::eColorChanged) {
3396 if (layer->setColor(s.color))
3397 flags |= eTraversalNeeded;
3398 }
3399 if (what & layer_state_t::eMatrixChanged) {
3400 if (layer->setMatrix(s.matrix))
3401 flags |= eTraversalNeeded;
3402 }
3403 if (what & layer_state_t::eTransparentRegionChanged) {
3404 if (layer->setTransparentRegionHint(s.transparentRegion))
3405 flags |= eTraversalNeeded;
3406 }
3407 if (what & layer_state_t::eFlagsChanged) {
3408 if (layer->setFlags(s.flags, s.mask))
3409 flags |= eTraversalNeeded;
3410 }
3411 if (what & layer_state_t::eCropChanged) {
3412 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3413 flags |= eTraversalNeeded;
3414 }
3415 if (what & layer_state_t::eFinalCropChanged) {
3416 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3417 flags |= eTraversalNeeded;
3418 }
3419 if (what & layer_state_t::eLayerStackChanged) {
3420 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3421 // We only allow setting layer stacks for top level layers,
3422 // everything else inherits layer stack from its parent.
3423 if (layer->hasParent()) {
3424 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3425 layer->getName().string());
3426 } else if (idx < 0) {
3427 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3428 "that also does not appear in the top level layer list. Something"
3429 " has gone wrong.", layer->getName().string());
3430 } else if (layer->setLayerStack(s.layerStack)) {
3431 mCurrentState.layersSortedByZ.removeAt(idx);
3432 mCurrentState.layersSortedByZ.add(layer);
3433 // we need traversal (state changed)
3434 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003435 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003436 }
3437 }
3438 if (what & layer_state_t::eDeferTransaction) {
3439 if (s.barrierHandle != nullptr) {
3440 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3441 } else if (s.barrierGbp != nullptr) {
3442 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3443 if (authenticateSurfaceTextureLocked(gbp)) {
3444 const auto& otherLayer =
3445 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3446 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3447 } else {
3448 ALOGE("Attempt to defer transaction to to an"
3449 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003450 }
3451 }
chaviw8b3871a2017-11-01 17:41:01 -07003452 // We don't trigger a traversal here because if no other state is
3453 // changed, we don't want this to cause any more work
3454 }
3455 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003456 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003457 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003458 if (!hadParent) {
3459 mCurrentState.layersSortedByZ.remove(layer);
3460 }
chaviw8b3871a2017-11-01 17:41:01 -07003461 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003462 }
chaviw8b3871a2017-11-01 17:41:01 -07003463 }
3464 if (what & layer_state_t::eReparentChildren) {
3465 if (layer->reparentChildren(s.reparentHandle)) {
3466 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003467 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003468 }
chaviw8b3871a2017-11-01 17:41:01 -07003469 if (what & layer_state_t::eDetachChildren) {
3470 layer->detachChildren();
3471 }
3472 if (what & layer_state_t::eOverrideScalingModeChanged) {
3473 layer->setOverrideScalingMode(s.overrideScalingMode);
3474 // We don't trigger a traversal here because if no other state is
3475 // changed, we don't want this to cause any more work
3476 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003477 return flags;
3478}
3479
chaviwca27f252018-02-06 16:46:39 -08003480void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3481 const layer_state_t& state = composerState.state;
3482 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3483
3484 sp<Layer> layer(client->getLayerUser(state.surface));
3485 if (layer == nullptr) {
3486 return;
3487 }
3488
3489 if (layer->isPendingRemoval()) {
3490 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3491 return;
3492 }
3493
3494 if (state.what & layer_state_t::eDestroySurface) {
3495 removeLayerLocked(mStateLock, layer);
3496 }
3497}
3498
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003499status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003500 const String8& name,
3501 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003502 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliuccd34842018-03-14 12:26:23 -07003503 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003504 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003505{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003506 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003507 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003508 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003509 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003510 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003511
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003512 status_t result = NO_ERROR;
3513
3514 sp<Layer> layer;
3515
Cody Northropbc755282017-03-31 12:00:08 -06003516 String8 uniqueName = getUniqueLayerName(name);
3517
Mathias Agopian3165cc22012-08-08 19:42:09 -07003518 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3519 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003520 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003521 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003522 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003523
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003524 break;
chaviw13fdc492017-06-27 12:40:18 -07003525 case ISurfaceComposerClient::eFXSurfaceColor:
3526 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003527 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003528 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003529 break;
3530 default:
3531 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003532 break;
3533 }
3534
Dan Stoza7d89d062015-04-30 13:29:25 -07003535 if (result != NO_ERROR) {
3536 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003537 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003538
Chia-I Wuab0c3192017-08-01 11:29:00 -07003539 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3540 // TODO b/64227542
3541 if (windowType == 441731) {
3542 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3543 layer->setPrimaryDisplayOnly();
3544 }
3545
Albert Chaulk479c60c2017-01-27 14:21:34 -05003546 layer->setInfo(windowType, ownerUid);
3547
Robert Carr1f0a16a2016-10-24 16:27:39 -07003548 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003549 if (result != NO_ERROR) {
3550 return result;
3551 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003552 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003553
3554 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003555 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003556}
3557
Cody Northropbc755282017-03-31 12:00:08 -06003558String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3559{
3560 bool matchFound = true;
3561 uint32_t dupeCounter = 0;
3562
3563 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3564 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3565
3566 // Loop over layers until we're sure there is no matching name
3567 while (matchFound) {
3568 matchFound = false;
3569 mDrawingState.traverseInZOrder([&](Layer* layer) {
3570 if (layer->getName() == uniqueName) {
3571 matchFound = true;
3572 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3573 }
3574 });
3575 }
3576
3577 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3578
3579 return uniqueName;
3580}
3581
David Sodman0c69cad2017-08-21 12:12:51 -07003582status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003583 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3584 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003585{
3586 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003587 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003588 case PIXEL_FORMAT_TRANSPARENT:
3589 case PIXEL_FORMAT_TRANSLUCENT:
3590 format = PIXEL_FORMAT_RGBA_8888;
3591 break;
3592 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003593 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003594 break;
3595 }
3596
David Sodman0c69cad2017-08-21 12:12:51 -07003597 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3598 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003599 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003600 *handle = layer->getHandle();
3601 *gbp = layer->getProducer();
3602 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003603 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003604
David Sodman0c69cad2017-08-21 12:12:51 -07003605 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003606 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003607}
3608
chaviw13fdc492017-06-27 12:40:18 -07003609status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003610 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003611 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003612{
chaviw13fdc492017-06-27 12:40:18 -07003613 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003614 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003615 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003616}
3617
Mathias Agopianac9fa422013-02-11 16:40:36 -08003618status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003619{
Robert Carr9524cb32017-02-13 11:32:32 -08003620 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003621 status_t err = NO_ERROR;
3622 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003623 if (l != nullptr) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003624 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003625 err = removeLayer(l);
3626 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3627 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003628 }
3629 return err;
3630}
3631
Mathias Agopian13127d82013-03-05 17:47:11 -08003632status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003633{
Mathias Agopian67106042013-03-14 19:18:13 -07003634 // called by ~LayerCleaner() when all references to the IBinder (handle)
3635 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003636 sp<Layer> l = layer.promote();
3637 if (l == nullptr) {
3638 // The layer has already been removed, carry on
3639 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003640 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003641 // If we have a parent, then we can continue to live as long as it does.
3642 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003643}
3644
Mathias Agopianb60314a2012-04-10 22:09:54 -07003645// ---------------------------------------------------------------------------
3646
Andy McFadden13a082e2012-08-24 10:16:42 -07003647void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003648 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003649 Vector<ComposerState> state;
3650 Vector<DisplayState> displays;
3651 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003652 d.what = DisplayState::eDisplayProjectionChanged |
3653 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003654 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003655 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003656 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003657 d.frame.makeInvalid();
3658 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003659 d.width = 0;
3660 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003661 displays.add(d);
3662 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003663 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3664 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003665
David Sodman105b7dc2017-11-04 20:28:14 -07003666 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003667 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003668 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003669
Brian Andersond0010582017-03-07 13:20:31 -08003670 // Use phase of 0 since phase is not known.
3671 // Use latency of 0, which will snap to the ideal latency.
3672 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003673}
3674
3675void SurfaceFlinger::initializeDisplays() {
3676 class MessageScreenInitialized : public MessageBase {
3677 SurfaceFlinger* flinger;
3678 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003679 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003680 virtual bool handler() {
3681 flinger->onInitializeDisplays();
3682 return true;
3683 }
3684 };
3685 sp<MessageBase> msg = new MessageScreenInitialized(this);
3686 postMessageAsync(msg); // we may be called from main thread, use async message
3687}
3688
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003689void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003690 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003691 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3692 this);
3693 int32_t type = hw->getDisplayType();
3694 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003695
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003696 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003697 return;
3698 }
3699
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003700 hw->setPowerMode(mode);
3701 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3702 ALOGW("Trying to set power mode for virtual display");
3703 return;
3704 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003705
Lloyd Pique4d234852018-01-22 17:21:36 -08003706 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003707 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003708 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3709 if (idx < 0) {
3710 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3711 return;
3712 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003713 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003714 }
3715
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003716 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003717 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003718 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003719 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3720 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003721 // FIXME: eventthread only knows about the main display right now
3722 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003723 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003724 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003725
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003726 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003727 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003728 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003729
3730 struct sched_param param = {0};
3731 param.sched_priority = 1;
3732 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3733 ALOGW("Couldn't set SCHED_FIFO on display on");
3734 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003735 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003736 // Turn off the display
3737 struct sched_param param = {0};
3738 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3739 ALOGW("Couldn't set SCHED_OTHER on display off");
3740 }
3741
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003742 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3743 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003744 disableHardwareVsync(true); // also cancels any in-progress resync
3745
Mathias Agopiancde87a32012-09-13 14:09:01 -07003746 // FIXME: eventthread only knows about the main display right now
3747 mEventThread->onScreenReleased();
3748 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003749
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003750 getHwComposer().setPowerMode(type, mode);
3751 mVisibleRegionsDirty = true;
3752 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003753 } else if (mode == HWC_POWER_MODE_DOZE ||
3754 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003755 // Update display while dozing
3756 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003757 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3758 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003759 // FIXME: eventthread only knows about the main display right now
3760 mEventThread->onScreenAcquired();
3761 resyncToHardwareVsync(true);
3762 }
3763 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3764 // Leave display going to doze
3765 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3766 disableHardwareVsync(true); // also cancels any in-progress resync
3767 // FIXME: eventthread only knows about the main display right now
3768 mEventThread->onScreenReleased();
3769 }
3770 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003771 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003772 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003773 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003774 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003775 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003776}
3777
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003778void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3779 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003780 SurfaceFlinger& mFlinger;
3781 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003782 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003783 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003784 MessageSetPowerMode(SurfaceFlinger& flinger,
3785 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3786 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003787 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003788 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003789 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003790 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003791 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003792 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003793 ALOGW("Attempt to set power mode = %d for virtual display",
3794 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003795 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003796 mFlinger.setPowerModeInternal(
3797 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003798 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003799 return true;
3800 }
3801 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003802 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003803 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003804}
3805
3806// ---------------------------------------------------------------------------
3807
Lloyd Pique755e3192018-01-31 16:46:15 -08003808status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3809 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003810 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003811
Mathias Agopianbd115332013-04-18 16:41:04 -07003812 IPCThreadState* ipc = IPCThreadState::self();
3813 const int pid = ipc->getCallingPid();
3814 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003815
Mathias Agopianbd115332013-04-18 16:41:04 -07003816 if ((uid != AID_SHELL) &&
3817 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003818 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003819 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003820 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003821 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003822 // (this would indicate SF is stuck, but we want to be able to
3823 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003824 status_t err = mStateLock.timedLock(s2ns(1));
3825 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003826 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003827 result.appendFormat(
3828 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3829 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003830 }
3831
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003832 bool dumpAll = true;
3833 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003834 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003835
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003836 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003837 if ((index < numArgs) &&
3838 (args[index] == String16("--list"))) {
3839 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003840 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003841 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003842 }
3843
3844 if ((index < numArgs) &&
3845 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003846 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003847 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003848 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003849 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003850
3851 if ((index < numArgs) &&
3852 (args[index] == String16("--latency-clear"))) {
3853 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003854 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003855 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003856 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003857
3858 if ((index < numArgs) &&
3859 (args[index] == String16("--dispsync"))) {
3860 index++;
3861 mPrimaryDispSync.dump(result);
3862 dumpAll = false;
3863 }
Dan Stozab90cf072015-03-05 11:05:59 -08003864
3865 if ((index < numArgs) &&
3866 (args[index] == String16("--static-screen"))) {
3867 index++;
3868 dumpStaticScreenStats(result);
3869 dumpAll = false;
3870 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003871
3872 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003873 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003874 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003875 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003876 dumpAll = false;
3877 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003878
3879 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3880 index++;
3881 dumpWideColorInfo(result);
3882 dumpAll = false;
3883 }
Yiwei Zhang068e31b2018-02-21 13:02:45 -08003884
3885 if ((index < numArgs) &&
3886 (args[index] == String16("--enable-layer-stats"))) {
3887 index++;
3888 mLayerStats.enable();
3889 dumpAll = false;
3890 }
3891
3892 if ((index < numArgs) &&
3893 (args[index] == String16("--disable-layer-stats"))) {
3894 index++;
3895 mLayerStats.disable();
3896 dumpAll = false;
3897 }
3898
3899 if ((index < numArgs) &&
3900 (args[index] == String16("--clear-layer-stats"))) {
3901 index++;
3902 mLayerStats.clear();
3903 dumpAll = false;
3904 }
3905
3906 if ((index < numArgs) &&
3907 (args[index] == String16("--dump-layer-stats"))) {
3908 index++;
3909 mLayerStats.dump(result);
3910 dumpAll = false;
3911 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -07003912
3913 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3914 index++;
3915 mTimeStats.parseArgs(asProto, args, index, result);
3916 dumpAll = false;
3917 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003918 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003919
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003920 if (dumpAll) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -07003921 if (asProto) {
3922 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3923 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3924 } else {
3925 dumpAllLocked(args, index, result);
3926 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08003927 }
3928
Mathias Agopian9795c422009-08-26 16:36:26 -07003929 if (locked) {
3930 mStateLock.unlock();
3931 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003932 }
3933 write(fd, result.string(), result.size());
3934 return NO_ERROR;
3935}
3936
Dan Stozac7014012014-02-14 15:03:43 -08003937void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3938 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003939{
Robert Carr2047fae2016-11-28 14:09:09 -08003940 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003941 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003942 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003943}
3944
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003945void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003946 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003947{
3948 String8 name;
3949 if (index < args.size()) {
3950 name = String8(args[index]);
3951 index++;
3952 }
3953
David Sodman105b7dc2017-11-04 20:28:14 -07003954 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003955 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003956 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003957
3958 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003959 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003960 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003961 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003962 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003963 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003964 }
Robert Carr2047fae2016-11-28 14:09:09 -08003965 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003966 }
3967}
3968
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003969void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003970 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003971{
3972 String8 name;
3973 if (index < args.size()) {
3974 name = String8(args[index]);
3975 index++;
3976 }
3977
Robert Carr2047fae2016-11-28 14:09:09 -08003978 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003979 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003980 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003981 }
Robert Carr2047fae2016-11-28 14:09:09 -08003982 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003983
Svetoslavd85084b2014-03-20 10:28:31 -07003984 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003985}
3986
Jamie Gennis6547ff42013-07-16 20:12:42 -07003987// This should only be called from the main thread. Otherwise it would need
3988// the lock and should use mCurrentState rather than mDrawingState.
3989void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003990 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003991 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003992 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003993
3994 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3995}
3996
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003997void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003998{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003999 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004000
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004001 if (isLayerTripleBufferingDisabled())
4002 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004003
4004 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004005 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004006 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004007 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004008 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4009 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004010 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004011}
4012
Dan Stozab90cf072015-03-05 11:05:59 -08004013void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4014{
4015 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004016 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4017 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004018 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004019 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004020 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4021 b + 1, bucketTimeSec, percent);
4022 }
David Sodman4a36e932017-11-07 14:29:47 -08004023 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004024 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004025 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004026 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004027 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004028}
4029
Dan Stozae77c7662016-05-13 11:37:28 -07004030void SurfaceFlinger::recordBufferingStats(const char* layerName,
4031 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004032 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4033 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004034 for (const auto& segment : history) {
4035 if (!segment.usedThirdBuffer) {
4036 stats.twoBufferTime += segment.totalTime;
4037 }
4038 if (segment.occupancyAverage < 1.0f) {
4039 stats.doubleBufferedTime += segment.totalTime;
4040 } else if (segment.occupancyAverage < 2.0f) {
4041 stats.tripleBufferedTime += segment.totalTime;
4042 }
4043 ++stats.numSegments;
4044 stats.totalTime += segment.totalTime;
4045 }
4046}
4047
Brian Andersond6927fb2016-07-23 23:37:30 -07004048void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4049 result.appendFormat("Layer frame timestamps:\n");
4050
4051 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4052 const size_t count = currentLayers.size();
4053 for (size_t i=0 ; i<count ; i++) {
4054 currentLayers[i]->dumpFrameEvents(result);
4055 }
4056}
4057
Dan Stozae77c7662016-05-13 11:37:28 -07004058void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4059 result.append("Buffering stats:\n");
4060 result.append(" [Layer name] <Active time> <Two buffer> "
4061 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004062 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004063 typedef std::tuple<std::string, float, float, float> BufferTuple;
4064 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004065 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004066 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004067 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004068 if (stats.numSegments == 0) {
4069 continue;
4070 }
4071 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4072 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4073 stats.totalTime;
4074 float doubleBufferRatio = static_cast<float>(
4075 stats.doubleBufferedTime) / stats.totalTime;
4076 float tripleBufferRatio = static_cast<float>(
4077 stats.tripleBufferedTime) / stats.totalTime;
4078 sorted.insert({activeTime, {name, twoBufferRatio,
4079 doubleBufferRatio, tripleBufferRatio}});
4080 }
4081 for (const auto& sortedPair : sorted) {
4082 float activeTime = sortedPair.first;
4083 const BufferTuple& values = sortedPair.second;
4084 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4085 std::get<0>(values).c_str(), activeTime,
4086 std::get<1>(values), std::get<2>(values),
4087 std::get<3>(values));
4088 }
4089 result.append("\n");
4090}
4091
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004092void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4093 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004094 result.appendFormat("DisplayColorSetting: %d\n", mDisplayColorSetting);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004095
4096 // TODO: print out if wide-color mode is active or not
4097
4098 for (size_t d = 0; d < mDisplays.size(); d++) {
4099 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4100 int32_t hwcId = displayDevice->getHwcDisplayId();
4101 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4102 continue;
4103 }
4104
4105 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004106 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004107 for (auto&& mode : modes) {
4108 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4109 }
4110
Peiyong Lina52f0292018-03-14 17:26:31 -07004111 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004112 result.appendFormat(" Current color mode: %s (%d)\n",
4113 decodeColorMode(currentMode).c_str(), currentMode);
4114 }
4115 result.append("\n");
4116}
4117
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004118LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004119 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004120 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4121 const State& state = useDrawing ? mDrawingState : mCurrentState;
4122 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004123 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004124 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004125 });
4126
4127 return layersProto;
4128}
4129
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004130LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4131 LayersProto layersProto;
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004132 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004133
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004134 SizeProto* resolution = layersProto.mutable_resolution();
4135 resolution->set_w(displayDevice->getWidth());
4136 resolution->set_h(displayDevice->getHeight());
4137
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004138 layersProto.set_color_mode(decodeColorMode(displayDevice->getActiveColorMode()));
4139 layersProto.set_color_transform(decodeColorTransform(displayDevice->getColorTransform()));
4140 layersProto.set_global_transform(
4141 static_cast<int32_t>(displayDevice->getOrientationTransform()));
4142
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004143 mDrawingState.traverseInZOrder([&](Layer* layer) {
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004144 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004145 LayerProto* layerProto = layersProto.add_layers();
4146 layer->writeToProto(layerProto, hwcId);
4147 }
4148 });
4149
4150 return layersProto;
4151}
4152
Mathias Agopian74d211a2013-04-22 16:55:35 +02004153void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4154 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004155{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004156 bool colorize = false;
4157 if (index < args.size()
4158 && (args[index] == String16("--color"))) {
4159 colorize = true;
4160 index++;
4161 }
4162
4163 Colorizer colorizer(colorize);
4164
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004165 // figure out if we're stuck somewhere
4166 const nsecs_t now = systemTime();
4167 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4168 const nsecs_t inTransaction(mDebugInTransaction);
4169 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4170 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4171
4172 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004173 * Dump library configuration.
4174 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004175
4176 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004177 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004178 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004179 appendSfConfigString(result);
4180 appendUiConfigString(result);
4181 appendGuiConfigString(result);
4182 result.append("\n");
4183
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004184 result.append("\nWide-Color information:\n");
4185 dumpWideColorInfo(result);
4186
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004187 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004188 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004189 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004190 result.append(SyncFeatures::getInstance().toString());
4191 result.append("\n");
4192
David Sodman105b7dc2017-11-04 20:28:14 -07004193 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004194
Andy McFadden41d67d72014-04-25 16:58:34 -07004195 colorizer.bold(result);
4196 result.append("DispSync configuration: ");
4197 colorizer.reset(result);
Dan Stoza2713c302018-03-28 17:07:36 -07004198 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, early sf phase %" PRId64
4199 " ns, present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4200 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, mVsyncModulator.getEarlyPhaseOffset(),
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004201 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004202 result.append("\n");
4203
Dan Stozab90cf072015-03-05 11:05:59 -08004204 // Dump static screen stats
4205 result.append("\n");
4206 dumpStaticScreenStats(result);
4207 result.append("\n");
4208
Dan Stozae77c7662016-05-13 11:37:28 -07004209 dumpBufferingStats(result);
4210
Andy McFadden4803b742012-09-24 19:07:20 -07004211 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004212 * Dump the visible layer list
4213 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004214 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004215 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004216 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4217 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004218 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004219
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004220 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004221 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7794ec12018-03-14 13:28:39 -07004222 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004223 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004224
4225 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004226 * Dump Display state
4227 */
4228
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004229 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004230 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004231 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004232 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4233 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004234 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004235 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004236 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004237
4238 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004239 * Dump SurfaceFlinger global state
4240 */
4241
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004242 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004243 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004244 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004245
Mathias Agopian888c8222012-08-04 21:10:38 -07004246 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004247 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004248
David Sodmanbc815282017-11-05 18:57:52 -08004249 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004250
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004251 if (hw) {
4252 hw->undefinedRegion.dump(result, "undefinedRegion");
4253 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4254 hw->getOrientation(), hw->isDisplayOn());
4255 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004256 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004257 " last eglSwapBuffers() time: %f us\n"
4258 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004259 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004260 " refresh-rate : %f fps\n"
4261 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004262 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004263 " gpu_to_cpu_unsupported : %d\n"
4264 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004265 mLastSwapBufferTime/1000.0,
4266 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004267 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004268 1e9 / activeConfig->getVsyncPeriod(),
4269 activeConfig->getDpiX(),
4270 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004271 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004272
Mathias Agopian74d211a2013-04-22 16:55:35 +02004273 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004274 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004275
Mathias Agopian74d211a2013-04-22 16:55:35 +02004276 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004277 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004278
4279 /*
4280 * VSYNC state
4281 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004282 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004283 result.append("\n");
4284
4285 /*
4286 * HWC layer minidump
4287 */
4288 for (size_t d = 0; d < mDisplays.size(); d++) {
4289 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4290 int32_t hwcId = displayDevice->getHwcDisplayId();
4291 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4292 continue;
4293 }
4294
4295 result.appendFormat("Display %d HWC layers:\n", hwcId);
4296 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004297 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004298 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004299 });
Dan Stozae22aec72016-08-01 13:20:59 -07004300 result.append("\n");
4301 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004302
4303 /*
4304 * Dump HWComposer state
4305 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004306 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004307 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004308 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004309 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004310 result.appendFormat(" h/w composer %s\n",
4311 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004312 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004313
4314 /*
4315 * Dump gralloc state
4316 */
4317 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4318 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004319
4320 /*
4321 * Dump VrFlinger state if in use.
4322 */
4323 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4324 result.append("VrFlinger state:\n");
4325 result.append(mVrFlinger->Dump().c_str());
4326 result.append("\n");
4327 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004328}
4329
Mathias Agopian13127d82013-03-05 17:47:11 -08004330const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004331SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004332 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004333 wp<IBinder> dpy;
4334 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4335 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4336 dpy = mDisplays.keyAt(i);
4337 break;
4338 }
4339 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004340 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004341 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4342 // Just use the primary display so we have something to return
4343 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4344 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004345 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004346}
4347
Keun young Park63f165f2012-08-31 10:53:36 -07004348bool SurfaceFlinger::startDdmConnection()
4349{
4350 void* libddmconnection_dso =
4351 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4352 if (!libddmconnection_dso) {
4353 return false;
4354 }
4355 void (*DdmConnection_start)(const char* name);
4356 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004357 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004358 if (!DdmConnection_start) {
4359 dlclose(libddmconnection_dso);
4360 return false;
4361 }
4362 (*DdmConnection_start)(getServiceName());
4363 return true;
4364}
4365
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004366status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004367 switch (code) {
4368 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004369 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004370 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004371 case CLEAR_ANIMATION_FRAME_STATS:
4372 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004373 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004374 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004375 case ENABLE_VSYNC_INJECTIONS:
4376 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004377 {
4378 // codes that require permission check
4379 IPCThreadState* ipc = IPCThreadState::self();
4380 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004381 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004382 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004383 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004384 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004385 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004386 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004387 break;
4388 }
Robert Carr1db73f62016-12-21 12:58:51 -08004389 /*
4390 * Calling setTransactionState is safe, because you need to have been
4391 * granted a reference to Client* and Handle* to do anything with it.
4392 *
4393 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4394 */
4395 case SET_TRANSACTION_STATE:
4396 case CREATE_SCOPED_CONNECTION:
4397 {
4398 return OK;
4399 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004400 case CAPTURE_SCREEN:
4401 {
4402 // codes that require permission check
4403 IPCThreadState* ipc = IPCThreadState::self();
4404 const int pid = ipc->getCallingPid();
4405 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004406 if ((uid != AID_GRAPHICS) &&
4407 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004408 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004409 return PERMISSION_DENIED;
4410 }
4411 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004412 }
chaviwa76b2712017-09-20 12:02:26 -07004413 case CAPTURE_LAYERS: {
4414 IPCThreadState* ipc = IPCThreadState::self();
4415 const int pid = ipc->getCallingPid();
4416 const int uid = ipc->getCallingUid();
4417 if ((uid != AID_GRAPHICS) &&
4418 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4419 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4420 return PERMISSION_DENIED;
4421 }
4422 break;
4423 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004424 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004425 return OK;
4426}
4427
4428status_t SurfaceFlinger::onTransact(
4429 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4430{
4431 status_t credentialCheck = CheckTransactCodeCredentials(code);
4432 if (credentialCheck != OK) {
4433 return credentialCheck;
4434 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004435
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004436 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4437 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004438 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004439 IPCThreadState* ipc = IPCThreadState::self();
4440 const int uid = ipc->getCallingUid();
4441 if (CC_UNLIKELY(uid != AID_SYSTEM
4442 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004443 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004444 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004445 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004446 return PERMISSION_DENIED;
4447 }
4448 int n;
4449 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004450 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004451 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004452 return NO_ERROR;
4453 case 1002: // SHOW_UPDATES
4454 n = data.readInt32();
4455 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004456 invalidateHwcGeometry();
4457 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004458 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004459 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004460 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004461 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004462 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004463 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004464 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004465 setTransactionFlags(
4466 eTransactionNeeded|
4467 eDisplayTransactionNeeded|
4468 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004469 return NO_ERROR;
4470 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004471 case 1006:{ // send empty update
4472 signalRefresh();
4473 return NO_ERROR;
4474 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004475 case 1008: // toggle use of hw composer
4476 n = data.readInt32();
4477 mDebugDisableHWC = n ? 1 : 0;
4478 invalidateHwcGeometry();
4479 repaintEverything();
4480 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004481 case 1009: // toggle use of transform hint
4482 n = data.readInt32();
4483 mDebugDisableTransformHint = n ? 1 : 0;
4484 invalidateHwcGeometry();
4485 repaintEverything();
4486 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004487 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004488 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004489 reply->writeInt32(0);
4490 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004491 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004492 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004493 return NO_ERROR;
4494 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004495 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004496 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004497 return NO_ERROR;
4498 }
4499 case 1014: {
4500 // daltonize
4501 n = data.readInt32();
4502 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004503 case 1:
4504 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4505 break;
4506 case 2:
4507 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4508 break;
4509 case 3:
4510 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4511 break;
4512 default:
4513 mDaltonizer.setType(ColorBlindnessType::None);
4514 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004515 }
4516 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004517 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004518 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004519 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004520 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004521 invalidateHwcGeometry();
4522 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004523 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004524 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004525 case 1015: {
4526 // apply a color matrix
4527 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004528 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004529 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004530 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004531 for (size_t j = 0; j < 4; j++) {
4532 mColorMatrix[i][j] = data.readFloat();
4533 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004534 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004535 } else {
4536 mColorMatrix = mat4();
4537 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004538
4539 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4540 // the division by w in the fragment shader
4541 float4 lastRow(transpose(mColorMatrix)[3]);
4542 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4543 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4544 }
4545
Alan Viverette9c5a3332013-09-12 20:04:35 -07004546 invalidateHwcGeometry();
4547 repaintEverything();
4548 return NO_ERROR;
4549 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004550 // This is an experimental interface
4551 // Needs to be shifted to proper binder interface when we productize
4552 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004553 n = data.readInt32();
4554 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004555 return NO_ERROR;
4556 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004557 case 1017: {
4558 n = data.readInt32();
4559 mForceFullDamage = static_cast<bool>(n);
4560 return NO_ERROR;
4561 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004562 case 1018: { // Modify Choreographer's phase offset
4563 n = data.readInt32();
4564 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4565 return NO_ERROR;
4566 }
4567 case 1019: { // Modify SurfaceFlinger's phase offset
4568 n = data.readInt32();
4569 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4570 return NO_ERROR;
4571 }
Irvel468051e2016-06-13 16:44:44 -07004572 case 1020: { // Layer updates interceptor
4573 n = data.readInt32();
4574 if (n) {
4575 ALOGV("Interceptor enabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004576 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004577 }
4578 else{
4579 ALOGV("Interceptor disabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004580 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004581 }
4582 return NO_ERROR;
4583 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004584 case 1021: { // Disable HWC virtual displays
4585 n = data.readInt32();
4586 mUseHwcVirtualDisplays = !n;
4587 return NO_ERROR;
4588 }
Romain Guy0147a172017-06-01 13:53:56 -07004589 case 1022: { // Set saturation boost
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004590 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004591
4592 invalidateHwcGeometry();
4593 repaintEverything();
4594 return NO_ERROR;
4595 }
Romain Guy54f154a2017-10-24 21:40:32 +01004596 case 1023: { // Set native mode
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004597 int32_t value = data.readInt32();
4598 if (value > 2) {
4599 return BAD_VALUE;
4600 }
4601 if (value == 2 && !mBuiltinDisplaySupportsEnhance) {
4602 return BAD_VALUE;
4603 }
Romain Guy54f154a2017-10-24 21:40:32 +01004604
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004605 mDisplayColorSetting = toDisplayColorSetting(value);
Romain Guy54f154a2017-10-24 21:40:32 +01004606 invalidateHwcGeometry();
4607 repaintEverything();
4608 return NO_ERROR;
4609 }
4610 case 1024: { // Is wide color gamut rendering/color management supported?
4611 reply->writeBool(hasWideColorDisplay);
4612 return NO_ERROR;
4613 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004614 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004615 n = data.readInt32();
4616 if (n) {
4617 ALOGV("LayerTracing enabled");
4618 mTracing.enable();
4619 doTracing("tracing.enable");
4620 reply->writeInt32(NO_ERROR);
4621 } else {
4622 ALOGV("LayerTracing disabled");
4623 status_t err = mTracing.disable();
4624 reply->writeInt32(err);
4625 }
4626 return NO_ERROR;
4627 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004628 case 1026: { // Get layer tracing status
4629 reply->writeBool(mTracing.isEnabled());
4630 return NO_ERROR;
4631 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004632 // Is a DisplayColorSetting supported?
4633 case 1027: {
4634 int32_t value = data.readInt32();
4635 switch (value) {
4636 case 0:
4637 reply->writeBool(hasWideColorDisplay);
4638 return NO_ERROR;
4639 case 1:
4640 reply->writeBool(true);
4641 return NO_ERROR;
4642 case 2:
4643 reply->writeBool(mBuiltinDisplaySupportsEnhance);
4644 return NO_ERROR;
4645 default:
4646 return BAD_VALUE;
4647 }
4648 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004649 }
4650 }
4651 return err;
4652}
4653
Steven Thomas6d8110b2017-08-31 18:24:21 -07004654void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004655 android_atomic_or(1, &mRepaintEverything);
4656 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004657}
4658
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004659// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4660class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004661public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004662 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4663 ~WindowDisconnector() {
4664 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004665 }
4666
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004667private:
4668 ANativeWindow* mWindow;
4669 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004670};
4671
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004672status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4673 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4674 int32_t minLayerZ, int32_t maxLayerZ,
4675 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004676 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004677 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004678
chaviwa76b2712017-09-20 12:02:26 -07004679 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4680
4681 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004682 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4683
chaviwa76b2712017-09-20 12:02:26 -07004684 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4685
4686 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4687 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004688 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004689}
4690
4691status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004692 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004693 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004694 ATRACE_CALL();
4695
4696 class LayerRenderArea : public RenderArea {
4697 public:
Robert Carr578038f2018-03-09 12:25:24 -08004698 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4699 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004700 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004701 mLayer(layer),
4702 mCrop(crop),
4703 mFlinger(flinger),
4704 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004705 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004706 Rect getBounds() const override {
4707 const Layer::State& layerState(mLayer->getDrawingState());
4708 return Rect(layerState.active.w, layerState.active.h);
4709 }
4710 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4711 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4712 bool isSecure() const override { return false; }
4713 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004714 Rect getSourceCrop() const override {
4715 if (mCrop.isEmpty()) {
4716 return getBounds();
4717 } else {
4718 return mCrop;
4719 }
4720 }
4721 bool getWideColorSupport() const override { return false; }
4722 Dataspace getDataSpace() const override { return Dataspace::UNKNOWN; }
Peiyong Linfb069302018-04-25 14:34:31 -07004723 float getDisplayMaxLuminance() const override {
4724 return DisplayDevice::sDefaultMaxLumiance;
4725 }
Robert Carr578038f2018-03-09 12:25:24 -08004726
4727 class ReparentForDrawing {
4728 public:
4729 const sp<Layer>& oldParent;
4730 const sp<Layer>& newParent;
4731
4732 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4733 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004734 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004735 }
Robert Carr15eae092018-03-23 13:43:53 -07004736 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004737 };
4738
4739 void render(std::function<void()> drawLayers) override {
4740 if (!mChildrenOnly) {
4741 mTransform = mLayer->getTransform().inverse();
4742 drawLayers();
4743 } else {
4744 Rect bounds = getBounds();
4745 screenshotParentLayer =
4746 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4747 bounds.getWidth(), bounds.getHeight(), 0);
4748
4749 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4750 drawLayers();
4751 }
4752 }
chaviwa76b2712017-09-20 12:02:26 -07004753
chaviwa76b2712017-09-20 12:02:26 -07004754 private:
chaviw7206d492017-11-10 16:16:12 -08004755 const sp<Layer> mLayer;
4756 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004757
4758 // In the "childrenOnly" case we reparent the children to a screenshot
4759 // layer which has no properties set and which does not draw.
4760 sp<ContainerLayer> screenshotParentLayer;
4761 Transform mTransform;
4762
4763 SurfaceFlinger* mFlinger;
4764 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004765 };
4766
4767 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4768 auto parent = layerHandle->owner.promote();
4769
chaviw7206d492017-11-10 16:16:12 -08004770 if (parent == nullptr || parent->isPendingRemoval()) {
4771 ALOGE("captureLayers called with a removed parent");
4772 return NAME_NOT_FOUND;
4773 }
4774
Robert Carr578038f2018-03-09 12:25:24 -08004775 const int uid = IPCThreadState::self()->getCallingUid();
4776 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4777 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4778 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4779 return PERMISSION_DENIED;
4780 }
4781
chaviw7206d492017-11-10 16:16:12 -08004782 Rect crop(sourceCrop);
4783 if (sourceCrop.width() <= 0) {
4784 crop.left = 0;
4785 crop.right = parent->getCurrentState().active.w;
4786 }
4787
4788 if (sourceCrop.height() <= 0) {
4789 crop.top = 0;
4790 crop.bottom = parent->getCurrentState().active.h;
4791 }
4792
4793 int32_t reqWidth = crop.width() * frameScale;
4794 int32_t reqHeight = crop.height() * frameScale;
4795
Robert Carr578038f2018-03-09 12:25:24 -08004796 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004797
Robert Carr578038f2018-03-09 12:25:24 -08004798 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004799 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4800 if (!layer->isVisible()) {
4801 return;
Robert Carr578038f2018-03-09 12:25:24 -08004802 } else if (childrenOnly && layer == parent.get()) {
4803 return;
chaviwa76b2712017-09-20 12:02:26 -07004804 }
4805 visitor(layer);
4806 });
4807 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004808 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004809}
4810
4811status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4812 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004813 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004814 bool useIdentityTransform) {
4815 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004816
chaviwa76b2712017-09-20 12:02:26 -07004817 renderArea.updateDimensions();
4818
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004819 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4820 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4821 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4822 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004823
4824 // This mutex protects syncFd and captureResult for communication of the return values from the
4825 // main thread back to this Binder thread
4826 std::mutex captureMutex;
4827 std::condition_variable captureCondition;
4828 std::unique_lock<std::mutex> captureLock(captureMutex);
4829 int syncFd = -1;
4830 std::optional<status_t> captureResult;
4831
Robert Carr03480e22018-01-04 16:02:06 -08004832 const int uid = IPCThreadState::self()->getCallingUid();
4833 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4834
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004835 sp<LambdaMessage> message = new LambdaMessage([&]() {
4836 // If there is a refresh pending, bug out early and tell the binder thread to try again
4837 // after the refresh.
4838 if (mRefreshPending) {
4839 ATRACE_NAME("Skipping screenshot for now");
4840 std::unique_lock<std::mutex> captureLock(captureMutex);
4841 captureResult = std::make_optional<status_t>(EAGAIN);
4842 captureCondition.notify_one();
4843 return;
4844 }
4845
4846 status_t result = NO_ERROR;
4847 int fd = -1;
4848 {
4849 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004850 renderArea.render([&]() {
4851 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4852 useIdentityTransform, forSystem, &fd);
4853 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004854 }
4855
4856 {
4857 std::unique_lock<std::mutex> captureLock(captureMutex);
4858 syncFd = fd;
4859 captureResult = std::make_optional<status_t>(result);
4860 captureCondition.notify_one();
4861 }
4862 });
4863
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004864 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004865 if (result == NO_ERROR) {
4866 captureCondition.wait(captureLock, [&]() { return captureResult; });
4867 while (*captureResult == EAGAIN) {
4868 captureResult.reset();
4869 result = postMessageAsync(message);
4870 if (result != NO_ERROR) {
4871 return result;
4872 }
4873 captureCondition.wait(captureLock, [&]() { return captureResult; });
4874 }
4875 result = *captureResult;
4876 }
4877
4878 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004879 sync_wait(syncFd, -1);
4880 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004881 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004882
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004883 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004884}
4885
chaviwa76b2712017-09-20 12:02:26 -07004886void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4887 TraverseLayersFunction traverseLayers, bool yswap,
4888 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004889 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004890
Lloyd Pique144e1162017-12-20 16:44:52 -08004891 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004892
4893 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004894 const auto raWidth = renderArea.getWidth();
4895 const auto raHeight = renderArea.getHeight();
4896
4897 const auto reqWidth = renderArea.getReqWidth();
4898 const auto reqHeight = renderArea.getReqHeight();
4899 Rect sourceCrop = renderArea.getSourceCrop();
4900
4901 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4902 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004903
Dan Stozac1879002014-05-22 15:59:05 -07004904 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004905 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004906 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004907 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004908 }
4909
4910 // ensure that sourceCrop is inside screen
4911 if (sourceCrop.left < 0) {
4912 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4913 }
chaviwa76b2712017-09-20 12:02:26 -07004914 if (sourceCrop.right > raWidth) {
4915 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004916 }
4917 if (sourceCrop.top < 0) {
4918 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4919 }
chaviwa76b2712017-09-20 12:02:26 -07004920 if (sourceCrop.bottom > raHeight) {
4921 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004922 }
4923
Peiyong Lin34beb7a2018-03-28 11:57:12 -07004924 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004925 if (renderArea.getWideColorSupport()) {
4926 outputDataspace = renderArea.getDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004927 }
Peiyong Linfb069302018-04-25 14:34:31 -07004928 engine.setOutputDataSpace(outputDataspace);
4929 engine.setDisplayMaxLuminance(renderArea.getDisplayMaxLuminance());
Romain Guy88d37dd2017-05-26 17:57:05 -07004930
Mathias Agopian180f10d2013-04-10 22:55:41 -07004931 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004932 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004933
4934 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004935 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4936 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004937 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004938
chaviw50da5042018-04-09 13:49:37 -07004939 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004940 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07004941 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004942
chaviwa76b2712017-09-20 12:02:26 -07004943 traverseLayers([&](Layer* layer) {
4944 if (filtering) layer->setFiltering(true);
4945 layer->draw(renderArea, useIdentityTransform);
4946 if (filtering) layer->setFiltering(false);
4947 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004948}
4949
chaviwa76b2712017-09-20 12:02:26 -07004950status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4951 TraverseLayersFunction traverseLayers,
4952 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004953 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08004954 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07004955 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004956 ATRACE_CALL();
4957
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004958 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004959
4960 traverseLayers([&](Layer* layer) {
4961 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4962 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004963
Robert Carr03480e22018-01-04 16:02:06 -08004964 // We allow the system server to take screenshots of secure layers for
4965 // use in situations like the Screen-rotation animation and place
4966 // the impetus on WindowManager to not persist them.
4967 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004968 ALOGW("FB is protected: PERMISSION_DENIED");
4969 return PERMISSION_DENIED;
4970 }
4971
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004972 // this binds the given EGLImage as a framebuffer for the
4973 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08004974 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08004975 if (bufferBond.getStatus() != NO_ERROR) {
4976 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004977 return INVALID_OPERATION;
4978 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004979
Dan Stozaabcda352017-06-01 14:37:39 -07004980 // this will in fact render into our dequeued buffer
4981 // via an FBO, which means we didn't have to create
4982 // an EGLSurface and therefore we're not
4983 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004984 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004985
Dan Stozaabcda352017-06-01 14:37:39 -07004986 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08004987 getRenderEngine().finish();
4988 *outSyncFd = -1;
4989
chaviwa76b2712017-09-20 12:02:26 -07004990 const auto reqWidth = renderArea.getReqWidth();
4991 const auto reqHeight = renderArea.getReqHeight();
4992
Dan Stozaabcda352017-06-01 14:37:39 -07004993 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4994 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004995 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004996 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08004997 } else {
4998 base::unique_fd syncFd = getRenderEngine().flush();
4999 if (syncFd < 0) {
5000 getRenderEngine().finish();
5001 }
5002 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005003 }
5004
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005005 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005006}
5007
Mathias Agopiand5556842013-09-19 17:08:37 -07005008void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005009 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005010 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005011 for (size_t y = 0; y < h; y++) {
5012 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5013 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005014 if (p[x] != 0xFF000000) return;
5015 }
5016 }
chaviwa76b2712017-09-20 12:02:26 -07005017 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005018
Robert Carr2047fae2016-11-28 14:09:09 -08005019 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005020 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005021 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005022 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5023 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5024 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5025 static_cast<float>(state.color.a));
5026 i++;
5027 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005028 }
5029}
5030
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005031// ---------------------------------------------------------------------------
5032
Dan Stoza412903f2017-04-27 13:42:17 -07005033void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5034 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005035}
5036
Dan Stoza412903f2017-04-27 13:42:17 -07005037void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5038 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005039}
5040
chaviwa76b2712017-09-20 12:02:26 -07005041void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
5042 int32_t maxLayerZ,
5043 const LayerVector::Visitor& visitor) {
5044 // We loop through the first level of layers without traversing,
5045 // as we need to interpret min/max layer Z in the top level Z space.
5046 for (const auto& layer : mDrawingState.layersSortedByZ) {
5047 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5048 continue;
5049 }
5050 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005051 // relative layers are traversed in Layer::traverseInZOrder
5052 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005053 continue;
5054 }
5055 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005056 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5057 return;
5058 }
chaviwa76b2712017-09-20 12:02:26 -07005059 if (!layer->isVisible()) {
5060 return;
5061 }
5062 visitor(layer);
5063 });
5064 }
5065}
5066
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005067}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005068
5069
5070#if defined(__gl_h_)
5071#error "don't include gl/gl.h in this file"
5072#endif
5073
5074#if defined(__gl2_h_)
5075#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005076#endif