blob: e661f035913a69095ffe6c43b87fcfd6f93bae52 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060040#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070041#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070042#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043
Jamie Gennis1a4d8832012-08-02 20:11:05 -070044#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070045#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080047#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080048#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070049
50#include <ui/GraphicBufferAllocator.h>
51#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080053
Mathias Agopiancde87a32012-09-13 14:09:01 -070054#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080055#include <utils/String8.h>
56#include <utils/String16.h>
57#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070058#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080059#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060
Mathias Agopian921e6ac2012-07-23 23:11:29 -070061#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070062#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063
Robert Carr578038f2018-03-09 12:25:24 -080064#include "BufferLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020065#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080066#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020067#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080068#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080069#include "DdmConnection.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070070#include "DispSync.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "DisplayDevice.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070072#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080073#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
Robert Carr578038f2018-03-09 12:25:24 -080078#include "clz.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Steven Thomasb02664d2017-07-26 18:48:28 -070080#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070081#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070082#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070083#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084
Mathias Agopianff2ed702013-09-01 21:36:12 -070085#include "Effects/Daltonizer.h"
86
Mathias Agopian875d8e12013-06-07 15:35:48 -070087#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070088#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070089
Jiyong Park4b20c2e2017-01-14 19:45:11 +090090#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090091#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090092
chaviw1d044282017-09-27 12:19:28 -070093#include <layerproto/LayerProtoParser.h>
94
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080095#define DISPLAY_COUNT 1
96
Mathias Agopianfee2b462013-07-03 12:34:01 -070097/*
98 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
99 * black pixels.
100 */
101#define DEBUG_SCREENSHOTS false
102
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800103namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700104
Jaesoo Lee43518572017-01-23 19:03:16 +0900105using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900106using namespace android::hardware::configstore::V1_0;
Peiyong Linfd997e02018-03-28 15:29:00 -0700107using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700108using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700109using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700110using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900111
Steven Thomasb02664d2017-07-26 18:48:28 -0700112namespace {
113class ConditionalLock {
114public:
115 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
116 if (lock) {
117 mMutex.lock();
118 }
119 }
120 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
121private:
122 Mutex& mMutex;
123 bool mLocked;
124};
125} // namespace anonymous
126
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800127// ---------------------------------------------------------------------------
128
Mathias Agopian99b49842011-06-27 16:05:52 -0700129const String16 sHardwareTest("android.permission.HARDWARE_TEST");
130const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
131const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
132const String16 sDump("android.permission.DUMP");
133
134// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800135int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
136int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700137int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700138bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800139uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800140bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800141bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800142int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800143// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600144bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700145
Kalle Raitaa099a242017-01-11 11:17:29 -0800146
147std::string getHwcServiceName() {
148 char value[PROPERTY_VALUE_MAX] = {};
149 property_get("debug.sf.hwc_service_name", value, "default");
150 ALOGI("Using HWComposer service: '%s'", value);
151 return std::string(value);
152}
153
154bool useTrebleTestingOverride() {
155 char value[PROPERTY_VALUE_MAX] = {};
156 property_get("debug.sf.treble_testing_override", value, "false");
157 ALOGI("Treble testing override: '%s'", value);
158 return std::string(value) == "true";
159}
160
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800161DisplayColorSetting toDisplayColorSetting(int value) {
162 switch(value) {
163 case 0:
164 return DisplayColorSetting::MANAGED;
165 case 1:
166 return DisplayColorSetting::UNMANAGED;
167 case 2:
168 return DisplayColorSetting::ENHANCED;
169 default:
170 return DisplayColorSetting::MANAGED;
171 }
172}
173
174std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
175 switch(displayColorSetting) {
176 case DisplayColorSetting::MANAGED:
177 return std::string("Natural Mode");
178 case DisplayColorSetting::UNMANAGED:
179 return std::string("Saturated Mode");
180 case DisplayColorSetting::ENHANCED:
181 return std::string("Auto Color Mode");
182 }
183 return std::string("Unknown Display Color Setting");
184}
185
Lloyd Pique09594832018-01-22 17:48:03 -0800186NativeWindowSurface::~NativeWindowSurface() = default;
187
188namespace impl {
189
190class NativeWindowSurface final : public android::NativeWindowSurface {
191public:
192 static std::unique_ptr<android::NativeWindowSurface> create(
193 const sp<IGraphicBufferProducer>& producer) {
194 return std::make_unique<NativeWindowSurface>(producer);
195 }
196
197 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
198 : surface(new Surface(producer, false)) {}
199
200 ~NativeWindowSurface() override = default;
201
202private:
203 sp<ANativeWindow> getNativeWindow() const override { return surface; }
204
205 void preallocateBuffers() override { surface->allocateBuffers(); }
206
207 sp<Surface> surface;
208};
209
210} // namespace impl
211
David Sodmanbc815282017-11-05 18:57:52 -0800212SurfaceFlingerBE::SurfaceFlingerBE()
213 : mHwcServiceName(getHwcServiceName()),
214 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800215 mFrameBuckets(),
216 mTotalTime(0),
217 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800218 mComposerSequenceId(0) {
219}
220
Lloyd Pique2d3ee6d2018-01-17 13:42:24 -0800221SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800222 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800223 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700224 mTransactionPending(false),
225 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700226 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700227 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700228 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800229 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800230 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800231 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800232 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800233 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800234 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700235 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700236 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700237 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700238 mDebugInSwapBuffers(0),
239 mLastSwapBufferTime(0),
240 mDebugInTransaction(0),
241 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700242 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700243 mForceFullDamage(false),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000244 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700245 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700246 mHWVsyncAvailable(false),
Romain Guya9638732017-06-01 12:05:21 -0700247 mHasColorMatrix(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800248 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800249 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700250 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800251 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique09594832018-01-22 17:48:03 -0800252 mCreateBufferQueue(&BufferQueue::createBufferQueue),
253 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Pique2d3ee6d2018-01-17 13:42:24 -0800254
255SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800256 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800257
258 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
259 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
260
261 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
262 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
263
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800264 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
265 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800266
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700267 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
268 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
269
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700270 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
271 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
272
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800273 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
274 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
275
Steven Thomas050b2c82017-03-06 11:45:16 -0800276 // Vr flinger is only enabled on Daydream ready devices.
277 useVrFlinger = getBool< ISurfaceFlingerConfigs,
278 &ISurfaceFlingerConfigs::useVrFlinger>(false);
279
Fabien Sanglard1971b632017-03-10 14:50:03 -0800280 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
281 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
282
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600283 hasWideColorDisplay =
284 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
285
David Sodman99974d22017-11-28 12:04:33 -0800286 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700287
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800288 // debugging stuff...
289 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700290
Mathias Agopianb4b17302013-03-20 18:36:41 -0700291 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700292 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700293
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800294 property_get("debug.sf.showupdates", value, "0");
295 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700296
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700297 property_get("debug.sf.ddms", value, "0");
298 mDebugDDMS = atoi(value);
299 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700300 if (!startDdmConnection()) {
301 // start failed, and DDMS debugging not enabled
302 mDebugDDMS = 0;
303 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700304 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700305 ALOGI_IF(mDebugRegion, "showupdates enabled");
306 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700307
308 property_get("debug.sf.disable_backpressure", value, "0");
309 mPropagateBackpressure = !atoi(value);
310 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700311
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800312 property_get("debug.sf.enable_hwc_vds", value, "0");
313 mUseHwcVirtualDisplays = atoi(value);
314 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800315
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800316 property_get("ro.sf.disable_triple_buffer", value, "1");
317 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800318 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700319
Dan Stoza0a0158c2018-03-16 13:38:54 -0700320 // TODO (b/74616334): Reduce the default value once we isolate the leak
321 const size_t defaultListSize = 4 * MAX_LAYERS;
322 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
323 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
324
Dan Stoza2713c302018-03-28 17:07:36 -0700325 property_get("debug.sf.early_phase_offset_ns", value, "0");
326 const int earlyWakeupOffsetOffsetNs = atoi(value);
327 ALOGI_IF(earlyWakeupOffsetOffsetNs != 0, "Enabling separate early offset");
328 mVsyncModulator.setPhaseOffsets(sfVsyncPhaseOffsetNs - earlyWakeupOffsetOffsetNs,
329 sfVsyncPhaseOffsetNs);
330
Romain Guy11d63f42017-07-20 12:47:14 -0700331 // We should be reading 'persist.sys.sf.color_saturation' here
332 // but since /data may be encrypted, we need to wait until after vold
333 // comes online to attempt to read the property. The property is
334 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800335
336 if (useTrebleTestingOverride()) {
337 // Without the override SurfaceFlinger cannot connect to HIDL
338 // services that are not listed in the manifests. Considered
339 // deriving the setting from the set service name, but it
340 // would be brittle if the name that's not 'default' is used
341 // for production purposes later on.
342 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
343 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800344}
345
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800346void SurfaceFlinger::onFirstRef()
347{
Lloyd Pique9123ae52018-01-22 17:14:00 -0800348 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800349}
350
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800351SurfaceFlinger::~SurfaceFlinger()
352{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800353}
354
Dan Stozac7014012014-02-14 15:03:43 -0800355void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800356{
357 // the window manager died on us. prepare its eulogy.
358
Andy McFadden13a082e2012-08-24 10:16:42 -0700359 // restore initial conditions (default device unblank, etc)
360 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800361
362 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700363 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800364}
365
Robert Carr1db73f62016-12-21 12:58:51 -0800366static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700367 status_t err = client->initCheck();
368 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800369 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800370 }
Robert Carr1db73f62016-12-21 12:58:51 -0800371 return nullptr;
372}
373
374sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
375 return initClient(new Client(this));
376}
377
378sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
379 const sp<IGraphicBufferProducer>& gbp) {
380 if (authenticateSurfaceTexture(gbp) == false) {
381 return nullptr;
382 }
383 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
384 if (layer == nullptr) {
385 return nullptr;
386 }
387
388 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800389}
390
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700391sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
392 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700393{
394 class DisplayToken : public BBinder {
395 sp<SurfaceFlinger> flinger;
396 virtual ~DisplayToken() {
397 // no more references, this display must be terminated
398 Mutex::Autolock _l(flinger->mStateLock);
399 flinger->mCurrentState.displays.removeItem(this);
400 flinger->setTransactionFlags(eDisplayTransactionNeeded);
401 }
402 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700403 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700404 : flinger(flinger) {
405 }
406 };
407
408 sp<BBinder> token = new DisplayToken(this);
409
410 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700411 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700412 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700413 mCurrentState.displays.add(token, info);
Lloyd Pique4d234852018-01-22 17:21:36 -0800414 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700415 return token;
416}
417
Jesse Hall6c913be2013-08-08 12:15:49 -0700418void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
419 Mutex::Autolock _l(mStateLock);
420
421 ssize_t idx = mCurrentState.displays.indexOfKey(display);
422 if (idx < 0) {
423 ALOGW("destroyDisplay: invalid display token");
424 return;
425 }
426
427 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
428 if (!info.isVirtualDisplay()) {
429 ALOGE("destroyDisplay called for non-virtual display");
430 return;
431 }
Lloyd Pique4d234852018-01-22 17:21:36 -0800432 mInterceptor->saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700433 mCurrentState.displays.removeItemsAt(idx);
434 setTransactionFlags(eDisplayTransactionNeeded);
435}
436
Mathias Agopiane57f2922012-08-09 16:29:12 -0700437sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700438 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700439 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800440 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700441 }
Jesse Hall692c7232012-11-08 15:41:56 -0800442 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700443}
444
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800445void SurfaceFlinger::bootFinished()
446{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700447 if (mStartPropertySetThread->join() != NO_ERROR) {
448 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800449 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800450 const nsecs_t now = systemTime();
451 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000452 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700453
454 // wait patiently for the window manager death
455 const String16 name("window");
456 sp<IBinder> window(defaultServiceManager()->getService(name));
457 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700458 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700459 }
460
Steven Thomas050b2c82017-03-06 11:45:16 -0800461 if (mVrFlinger) {
462 mVrFlinger->OnBootFinished();
463 }
464
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700465 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700466 // formerly we would just kill the process, but we now ask it to exit so it
467 // can choose where to stop the animation.
468 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700469
470 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
471 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
472 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700473
Thierry Strudel2924d012017-08-14 15:19:37 -0700474 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700475 readPersistentProperties();
476 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700477 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800478}
479
Mathias Agopian3f844832013-08-07 21:24:32 -0700480void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700481 class MessageDestroyGLTexture : public MessageBase {
Lloyd Pique144e1162017-12-20 16:44:52 -0800482 RE::RenderEngine& engine;
Mathias Agopian3f844832013-08-07 21:24:32 -0700483 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700484 public:
Lloyd Pique144e1162017-12-20 16:44:52 -0800485 MessageDestroyGLTexture(RE::RenderEngine& engine, uint32_t texture)
486 : engine(engine), texture(texture) {}
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700487 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700488 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700489 return true;
490 }
491 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700492 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700493}
494
Lloyd Piquee83f9312018-02-01 12:53:17 -0800495class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700496public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700497 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000498 const char* name) :
499 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700500 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700501 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000502 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
503 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700504 mDispSync(dispSync),
505 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700506 mVsyncMutex(),
507 mPhaseOffset(phaseOffset),
508 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700509
Lloyd Piquee83f9312018-02-01 12:53:17 -0800510 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700511
Lloyd Piquee83f9312018-02-01 12:53:17 -0800512 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700513 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700514 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000515 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700516 static_cast<DispSync::Callback*>(this));
517 if (err != NO_ERROR) {
518 ALOGE("error registering vsync callback: %s (%d)",
519 strerror(-err), err);
520 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700521 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700522 } else {
523 status_t err = mDispSync->removeEventListener(
524 static_cast<DispSync::Callback*>(this));
525 if (err != NO_ERROR) {
526 ALOGE("error unregistering vsync callback: %s (%d)",
527 strerror(-err), err);
528 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700529 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700530 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700531 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700532 }
533
Lloyd Piquee83f9312018-02-01 12:53:17 -0800534 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700535 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700536 mCallback = callback;
537 }
538
Lloyd Piquee83f9312018-02-01 12:53:17 -0800539 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700540 Mutex::Autolock lock(mVsyncMutex);
541
542 // Normalize phaseOffset to [0, period)
543 auto period = mDispSync->getPeriod();
544 phaseOffset %= period;
545 if (phaseOffset < 0) {
546 // If we're here, then phaseOffset is in (-period, 0). After this
547 // operation, it will be in (0, period)
548 phaseOffset += period;
549 }
550 mPhaseOffset = phaseOffset;
551
552 // If we're not enabled, we don't need to mess with the listeners
553 if (!mEnabled) {
554 return;
555 }
556
Dan Stoza2713c302018-03-28 17:07:36 -0700557 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
558 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700559 if (err != NO_ERROR) {
Dan Stoza2713c302018-03-28 17:07:36 -0700560 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700561 strerror(-err), err);
562 }
563 }
564
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700565private:
566 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800567 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700568 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700569 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700570 callback = mCallback;
571
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700572 if (mTraceVsync) {
573 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700574 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700575 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700576 }
577
Peiyong Lin566a3b42018-01-09 18:22:43 -0800578 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700579 callback->onVSyncEvent(when);
580 }
581 }
582
Tim Murray4a4e4a22016-04-19 16:29:23 +0000583 const char* const mName;
584
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700585 int mValue;
586
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700587 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700588 const String8 mVsyncOnLabel;
589 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700590
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700591 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700592
593 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800594 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700595
596 Mutex mVsyncMutex; // Protects the following
597 nsecs_t mPhaseOffset;
598 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700599};
600
Lloyd Piquee83f9312018-02-01 12:53:17 -0800601class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700602public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800603 InjectVSyncSource() = default;
604 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700605
Lloyd Piquee83f9312018-02-01 12:53:17 -0800606 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700607 std::lock_guard<std::mutex> lock(mCallbackMutex);
608 mCallback = callback;
609 }
610
Lloyd Piquee83f9312018-02-01 12:53:17 -0800611 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700612 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700613 if (mCallback) {
614 mCallback->onVSyncEvent(when);
615 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700616 }
617
Lloyd Piquee83f9312018-02-01 12:53:17 -0800618 void setVSyncEnabled(bool) override {}
619 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700620
621private:
622 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800623 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700624};
625
Wei Wangf9b05ee2017-07-19 20:59:39 -0700626// Do not call property_set on main thread which will be blocked by init
627// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700628void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700629 ALOGI( "SurfaceFlinger's main thread ready to run. "
630 "Initializing graphics H/W...");
631
Thierry Strudel2924d012017-08-14 15:19:37 -0700632 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900633
Steven Thomasb02664d2017-07-26 18:48:28 -0700634 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800635
Steven Thomasb02664d2017-07-26 18:48:28 -0700636 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800637 mEventThreadSource =
638 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
639 true, "app");
640 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(), *this, false,
641 "appEventThread");
642 mSfEventThreadSource =
643 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
644 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800645
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800646 mSFEventThread = std::make_unique<impl::EventThread>(mSfEventThreadSource.get(), *this, true,
647 "sfEventThread");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800648 mEventQueue->setEventThread(mSFEventThread.get());
Dan Stoza2713c302018-03-28 17:07:36 -0700649 mVsyncModulator.setEventThread(mSFEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800650
Steven Thomasb02664d2017-07-26 18:48:28 -0700651 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800652 getBE().mRenderEngine =
653 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
654 hasWideColorDisplay
655 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
656 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800657 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700658
659 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
660 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800661 getBE().mHwc.reset(
662 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700663 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800664 // Process any initial hotplug and resulting display changes.
665 processDisplayHotplugEventsLocked();
666 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
667 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800668
Lloyd Piquefcd86612017-12-14 17:15:36 -0800669 // make the default display GLContext current so that we can create textures
670 // when creating Layers (which may happens before we render something)
671 getDefaultDisplayDeviceLocked()->makeCurrent();
672
Steven Thomas050b2c82017-03-06 11:45:16 -0800673 if (useVrFlinger) {
674 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700675 // This callback is called from the vr flinger dispatch thread. We
676 // need to call signalTransaction(), which requires holding
677 // mStateLock when we're not on the main thread. Acquiring
678 // mStateLock from the vr flinger dispatch thread might trigger a
679 // deadlock in surface flinger (see b/66916578), so post a message
680 // to be handled on the main thread instead.
681 sp<LambdaMessage> message = new LambdaMessage([=]() {
682 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
683 mVrFlingerRequestsDisplay = requestDisplay;
684 signalTransaction();
685 });
686 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800687 };
David Sodman105b7dc2017-11-04 20:28:14 -0700688 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
689 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800690 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800691 if (!mVrFlinger) {
692 ALOGE("Failed to start vrflinger");
693 }
694 }
695
Lloyd Pique0c3a8832018-01-22 17:31:47 -0800696 mEventControlThread = std::make_unique<impl::EventControlThread>(
697 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700698
Mathias Agopian92a979a2012-08-02 18:32:23 -0700699 // initialize our drawing state
700 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700701
Andy McFadden13a082e2012-08-24 10:16:42 -0700702 // set initial conditions (e.g. unblank default device)
703 initializeDisplays();
704
David Sodmanbc815282017-11-05 18:57:52 -0800705 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700706
Wei Wangf9b05ee2017-07-19 20:59:39 -0700707 // Inform native graphics APIs whether the present timestamp is supported:
708 if (getHwComposer().hasCapability(
709 HWC2::Capability::PresentFenceIsNotReliable)) {
710 mStartPropertySetThread = new StartPropertySetThread(false);
711 } else {
712 mStartPropertySetThread = new StartPropertySetThread(true);
713 }
714
715 if (mStartPropertySetThread->Start() != NO_ERROR) {
716 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800717 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800718
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800719 mLegacySrgbSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(HWC_DISPLAY_PRIMARY,
720 Dataspace::SRGB_LINEAR);
721
Dan Stoza9e56aa02015-11-02 13:00:03 -0800722 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700723}
724
Romain Guy11d63f42017-07-20 12:47:14 -0700725void SurfaceFlinger::readPersistentProperties() {
726 char value[PROPERTY_VALUE_MAX];
727
728 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800729 mGlobalSaturationFactor = atof(value);
730 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100731
732 property_get("persist.sys.sf.native_mode", value, "0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800733 mDisplayColorSetting = toDisplayColorSetting(atoi(value));
734 ALOGV("Display Color Setting is set to %s.",
735 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Romain Guy11d63f42017-07-20 12:47:14 -0700736}
737
Mathias Agopiana67e4182012-06-19 17:26:12 -0700738void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800739 // Start boot animation service by setting a property mailbox
740 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700741 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800742 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700743 if (mStartPropertySetThread->join() != NO_ERROR) {
744 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800745 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700746}
747
Mathias Agopian875d8e12013-06-07 15:35:48 -0700748size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800749 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700750}
751
Mathias Agopian875d8e12013-06-07 15:35:48 -0700752size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800753 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700754}
755
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800756// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800757
Jamie Gennis582270d2011-08-17 18:19:00 -0700758bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800759 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800760 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800761 return authenticateSurfaceTextureLocked(bufferProducer);
762}
763
764bool SurfaceFlinger::authenticateSurfaceTextureLocked(
765 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800766 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800767 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800768}
769
Brian Anderson6b376712017-04-04 10:51:39 -0700770status_t SurfaceFlinger::getSupportedFrameTimestamps(
771 std::vector<FrameEvent>* outSupported) const {
772 *outSupported = {
773 FrameEvent::REQUESTED_PRESENT,
774 FrameEvent::ACQUIRE,
775 FrameEvent::LATCH,
776 FrameEvent::FIRST_REFRESH_START,
777 FrameEvent::LAST_REFRESH_START,
778 FrameEvent::GPU_COMPOSITION_DONE,
779 FrameEvent::DEQUEUE_READY,
780 FrameEvent::RELEASE,
781 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700782 ConditionalLock _l(mStateLock,
783 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700784 if (!getHwComposer().hasCapability(
785 HWC2::Capability::PresentFenceIsNotReliable)) {
786 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
787 }
788 return NO_ERROR;
789}
790
Dan Stoza7f7da322014-05-02 15:26:25 -0700791status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
792 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800793 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700794 return BAD_VALUE;
795 }
796
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500797 if (!display.get())
798 return NAME_NOT_FOUND;
799
Jesse Hall692c7232012-11-08 15:41:56 -0800800 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700801 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800802 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700803 type = i;
804 break;
805 }
806 }
807
808 if (type < 0) {
809 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700810 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700811
Mathias Agopian8b736f12012-08-13 17:54:26 -0700812 // TODO: Not sure if display density should handled by SF any longer
813 class Density {
814 static int getDensityFromProperty(char const* propName) {
815 char property[PROPERTY_VALUE_MAX];
816 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800817 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700818 density = atoi(property);
819 }
820 return density;
821 }
822 public:
823 static int getEmuDensity() {
824 return getDensityFromProperty("qemu.sf.lcd_density"); }
825 static int getBuildDensity() {
826 return getDensityFromProperty("ro.sf.lcd_density"); }
827 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700828
Dan Stoza7f7da322014-05-02 15:26:25 -0700829 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700830
Steven Thomas6d8110b2017-08-31 18:24:21 -0700831 ConditionalLock _l(mStateLock,
832 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800833 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700834 DisplayInfo info = DisplayInfo();
835
Dan Stoza9e56aa02015-11-02 13:00:03 -0800836 float xdpi = hwConfig->getDpiX();
837 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700838
839 if (type == DisplayDevice::DISPLAY_PRIMARY) {
840 // The density of the device is provided by a build property
841 float density = Density::getBuildDensity() / 160.0f;
842 if (density == 0) {
843 // the build doesn't provide a density -- this is wrong!
844 // use xdpi instead
845 ALOGE("ro.sf.lcd_density must be defined as a build property");
846 density = xdpi / 160.0f;
847 }
848 if (Density::getEmuDensity()) {
849 // if "qemu.sf.lcd_density" is specified, it overrides everything
850 xdpi = ydpi = density = Density::getEmuDensity();
851 density /= 160.0f;
852 }
853 info.density = density;
854
855 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700856 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800857 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700858 } else {
859 // TODO: where should this value come from?
860 static const int TV_DENSITY = 213;
861 info.density = TV_DENSITY / 160.0f;
862 info.orientation = 0;
863 }
864
Dan Stoza9e56aa02015-11-02 13:00:03 -0800865 info.w = hwConfig->getWidth();
866 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700867 info.xdpi = xdpi;
868 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800869 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900870 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800871
Andy McFadden91b2ca82014-06-13 14:04:23 -0700872 // This is how far in advance a buffer must be queued for
873 // presentation at a given time. If you want a buffer to appear
874 // on the screen at time N, you must submit the buffer before
875 // (N - presentationDeadline).
876 //
877 // Normally it's one full refresh period (to give SF a chance to
878 // latch the buffer), but this can be reduced by configuring a
879 // DispSync offset. Any additional delays introduced by the hardware
880 // composer or panel must be accounted for here.
881 //
882 // We add an additional 1ms to allow for processing time and
883 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800884 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800885 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700886
887 // All non-virtual displays are currently considered secure.
888 info.secure = true;
889
Michael Wright28f24d02016-07-12 13:30:53 -0700890 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700891 }
892
Dan Stoza7f7da322014-05-02 15:26:25 -0700893 return NO_ERROR;
894}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700895
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800896status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700897 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800898 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700899 return BAD_VALUE;
900 }
901
902 // FIXME for now we always return stats for the primary display
903 memset(stats, 0, sizeof(*stats));
904 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
905 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
906 return NO_ERROR;
907}
908
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700909int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800910 if (display == nullptr) {
911 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800912 return BAD_VALUE;
913 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700914
915 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800916 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700917 return device->getActiveConfig();
918 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700919
Dan Stoza24a42e92015-03-09 10:04:11 -0700920 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700921}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700922
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700923void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
924 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
925 this);
926 int32_t type = hw->getDisplayType();
927 int currentMode = hw->getActiveConfig();
928
929 if (mode == currentMode) {
930 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
931 return;
932 }
933
934 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
935 ALOGW("Trying to set config for virtual display");
936 return;
937 }
938
939 hw->setActiveConfig(mode);
940 getHwComposer().setActiveConfig(type, mode);
941}
942
943status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
944 class MessageSetActiveConfig: public MessageBase {
945 SurfaceFlinger& mFlinger;
946 sp<IBinder> mDisplay;
947 int mMode;
948 public:
949 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
950 int mode) :
951 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
952 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700953 Vector<DisplayInfo> configs;
954 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700955 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700956 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700957 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700958 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700959 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700960 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800961 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700962 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700963 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700964 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
965 ALOGW("Attempt to set active config = %d for virtual display",
966 mMode);
967 } else {
968 mFlinger.setActiveConfigInternal(hw, mMode);
969 }
970 return true;
971 }
972 };
973 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
974 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700975 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700976}
Michael Wright28f24d02016-07-12 13:30:53 -0700977status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -0700978 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700979 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
980 return BAD_VALUE;
981 }
982
983 if (!display.get()) {
984 return NAME_NOT_FOUND;
985 }
986
987 int32_t type = NAME_NOT_FOUND;
988 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
989 if (display == mBuiltinDisplays[i]) {
990 type = i;
991 break;
992 }
993 }
994
995 if (type < 0) {
996 return type;
997 }
998
Peiyong Lina52f0292018-03-14 17:26:31 -0700999 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001000 {
1001 ConditionalLock _l(mStateLock,
1002 std::this_thread::get_id() != mMainThreadId);
1003 modes = getHwComposer().getColorModes(type);
1004 }
Michael Wright28f24d02016-07-12 13:30:53 -07001005 outColorModes->clear();
1006 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1007
1008 return NO_ERROR;
1009}
1010
Peiyong Lina52f0292018-03-14 17:26:31 -07001011ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001012 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -07001013 if (device != nullptr) {
1014 return device->getActiveColorMode();
1015 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001016 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001017}
1018
1019void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001020 ColorMode mode, Dataspace dataSpace) {
Michael Wright28f24d02016-07-12 13:30:53 -07001021 int32_t type = hw->getDisplayType();
Peiyong Lina52f0292018-03-14 17:26:31 -07001022 ColorMode currentMode = hw->getActiveColorMode();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001023 Dataspace currentDataSpace = hw->getCompositionDataSpace();
Peiyong Lin38e9a562018-04-10 16:24:20 -07001024 RenderIntent currentRenderIntent = hw->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001025
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001026 // Natural Mode means it's color managed and the color must be right,
1027 // thus we pick RenderIntent::COLORIMETRIC as render intent.
1028 // Native Mode means the display is not color managed, and whichever
1029 // render intent is picked doesn't matter, thus return
1030 // RenderIntent::COLORIMETRIC as default here.
1031 RenderIntent renderIntent = RenderIntent::COLORIMETRIC;
1032
1033 // In Auto Color Mode, we want to strech to panel color space, right now
1034 // only the built-in display supports it.
1035 if (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
1036 mBuiltinDisplaySupportsEnhance &&
1037 hw->getDisplayType() == DisplayDevice::DISPLAY_PRIMARY) {
1038 renderIntent = RenderIntent::ENHANCE;
1039 }
Peiyong Lin38e9a562018-04-10 16:24:20 -07001040
1041 if (mode == currentMode && dataSpace == currentDataSpace &&
1042 renderIntent == currentRenderIntent) {
1043 return;
1044 }
1045
1046 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1047 ALOGW("Trying to set config for virtual display");
1048 return;
1049 }
1050
1051 hw->setActiveColorMode(mode);
1052 hw->setCompositionDataSpace(dataSpace);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001053 hw->setActiveRenderIntent(renderIntent);
1054 getHwComposer().setActiveColorMode(type, mode, renderIntent);
1055
1056 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
1057 decodeColorMode(mode).c_str(), mode,
1058 decodeRenderIntent(renderIntent).c_str(), renderIntent,
1059 hw->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001060}
1061
1062
1063status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001064 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -07001065 class MessageSetActiveColorMode: public MessageBase {
1066 SurfaceFlinger& mFlinger;
1067 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -07001068 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001069 public:
1070 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -07001071 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -07001072 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1073 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -07001074 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001075 mFlinger.getDisplayColorModes(mDisplay, &modes);
1076 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -07001077 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001078 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1079 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001080 return true;
1081 }
1082 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1083 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001084 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1085 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001086 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001087 ALOGW("Attempt to set active color mode %s %d for virtual display",
1088 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001089 } else {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001090 mFlinger.setActiveColorModeInternal(hw, mMode, Dataspace::UNKNOWN);
Michael Wright28f24d02016-07-12 13:30:53 -07001091 }
1092 return true;
1093 }
1094 };
1095 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1096 postMessageSync(msg);
1097 return NO_ERROR;
1098}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001099
Svetoslavd85084b2014-03-20 10:28:31 -07001100status_t SurfaceFlinger::clearAnimationFrameStats() {
1101 Mutex::Autolock _l(mStateLock);
1102 mAnimFrameTracker.clearStats();
1103 return NO_ERROR;
1104}
1105
1106status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1107 Mutex::Autolock _l(mStateLock);
1108 mAnimFrameTracker.getStats(outStats);
1109 return NO_ERROR;
1110}
1111
Dan Stozac4f471e2016-03-24 09:31:08 -07001112status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1113 HdrCapabilities* outCapabilities) const {
1114 Mutex::Autolock _l(mStateLock);
1115
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001116 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001117 if (displayDevice == nullptr) {
1118 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1119 return BAD_VALUE;
1120 }
1121
Peiyong Lin62665892018-04-16 11:07:44 -07001122 HdrCapabilities capabilities;
1123 int status = getBE().mHwc->getHdrCapabilities(
1124 displayDevice->getHwcDisplayId(), &capabilities);
1125 if (status == NO_ERROR) {
1126 if (displayDevice->hasWideColorGamut() &&
1127 !displayDevice->hasHDR10Support()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001128 // insert HDR10 as we will force client composition for HDR10
1129 // layers
Peiyong Lin62665892018-04-16 11:07:44 -07001130 std::vector<Hdr> types = capabilities.getSupportedHdrTypes();
1131 types.push_back(Hdr::HDR10);
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001132
1133 *outCapabilities = HdrCapabilities(types,
Peiyong Lin62665892018-04-16 11:07:44 -07001134 capabilities.getDesiredMaxLuminance(),
1135 capabilities.getDesiredMaxAverageLuminance(),
1136 capabilities.getDesiredMinLuminance());
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001137 } else {
Peiyong Lin62665892018-04-16 11:07:44 -07001138 *outCapabilities = std::move(capabilities);
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001139 }
Dan Stozac4f471e2016-03-24 09:31:08 -07001140 } else {
1141 return BAD_VALUE;
1142 }
1143
1144 return NO_ERROR;
1145}
1146
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001147status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001148 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1149 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001150
Chia-I Wu90f669f2017-10-05 14:24:41 -07001151 if (mInjectVSyncs == enable) {
1152 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001153 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001154
1155 if (enable) {
1156 ALOGV("VSync Injections enabled");
1157 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001158 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique0fcde1b2017-12-20 16:50:21 -08001159 mInjectorEventThread =
1160 std::make_unique<impl::EventThread>(mVSyncInjector.get(), *this, false,
1161 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001162 }
Lloyd Pique9123ae52018-01-22 17:14:00 -08001163 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001164 } else {
1165 ALOGV("VSync Injections disabled");
Lloyd Pique9123ae52018-01-22 17:14:00 -08001166 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001167 }
1168
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001169 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001170 });
1171 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001172 return NO_ERROR;
1173}
1174
1175status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001176 Mutex::Autolock _l(mStateLock);
1177
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001178 if (!mInjectVSyncs) {
1179 ALOGE("VSync Injections not enabled");
1180 return BAD_VALUE;
1181 }
1182 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1183 ALOGV("Injecting VSync inside SurfaceFlinger");
1184 mVSyncInjector->onInjectSyncEvent(when);
1185 }
1186 return NO_ERROR;
1187}
1188
Lloyd Pique755e3192018-01-31 16:46:15 -08001189status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1190 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001191 IPCThreadState* ipc = IPCThreadState::self();
1192 const int pid = ipc->getCallingPid();
1193 const int uid = ipc->getCallingUid();
1194 if ((uid != AID_SHELL) &&
1195 !PermissionCache::checkPermission(sDump, pid, uid)) {
1196 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1197 return PERMISSION_DENIED;
1198 }
1199
1200 // Try to acquire a lock for 1s, fail gracefully
1201 const status_t err = mStateLock.timedLock(s2ns(1));
1202 const bool locked = (err == NO_ERROR);
1203 if (!locked) {
1204 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1205 return TIMED_OUT;
1206 }
1207
1208 outLayers->clear();
1209 mCurrentState.traverseInZOrder([&](Layer* layer) {
1210 outLayers->push_back(layer->getLayerDebugInfo());
1211 });
1212
1213 mStateLock.unlock();
1214 return NO_ERROR;
1215}
1216
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001217// ----------------------------------------------------------------------------
1218
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001219sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1220 ISurfaceComposer::VsyncSource vsyncSource) {
1221 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1222 return mSFEventThread->createEventConnection();
1223 } else {
1224 return mEventThread->createEventConnection();
1225 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001226}
1227
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001228// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001229
1230void SurfaceFlinger::waitForEvent() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001231 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001232}
1233
1234void SurfaceFlinger::signalTransaction() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001235 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001236}
1237
1238void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001239 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001240}
1241
1242void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001243 mRefreshPending = true;
Lloyd Pique9123ae52018-01-22 17:14:00 -08001244 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001245}
1246
1247status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001248 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001249 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001250}
1251
1252status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001253 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001254 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001255 if (res == NO_ERROR) {
1256 msg->wait();
1257 }
1258 return res;
1259}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001260
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001261void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001262 do {
1263 waitForEvent();
1264 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001265}
1266
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001267void SurfaceFlinger::enableHardwareVsync() {
1268 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001269 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001270 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001271 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1272 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001273 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001274 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001275}
1276
Jesse Hall948fe0c2013-10-14 12:56:09 -07001277void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001278 Mutex::Autolock _l(mHWVsyncLock);
1279
Jesse Hall948fe0c2013-10-14 12:56:09 -07001280 if (makeAvailable) {
1281 mHWVsyncAvailable = true;
1282 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001283 // Hardware vsync is not currently available, so abort the resync
1284 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001285 return;
1286 }
1287
David Sodman105b7dc2017-11-04 20:28:14 -07001288 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001289 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001290
1291 mPrimaryDispSync.reset();
1292 mPrimaryDispSync.setPeriod(period);
1293
1294 if (!mPrimaryHWVsyncEnabled) {
1295 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001296 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1297 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001298 mPrimaryHWVsyncEnabled = true;
1299 }
1300}
1301
Jesse Hall948fe0c2013-10-14 12:56:09 -07001302void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001303 Mutex::Autolock _l(mHWVsyncLock);
1304 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001305 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1306 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001307 mPrimaryDispSync.endResync();
1308 mPrimaryHWVsyncEnabled = false;
1309 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001310 if (makeUnavailable) {
1311 mHWVsyncAvailable = false;
1312 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001313}
1314
Tim Murray4a4e4a22016-04-19 16:29:23 +00001315void SurfaceFlinger::resyncWithRateLimit() {
1316 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001317
1318 // No explicit locking is needed here since EventThread holds a lock while calling this method
1319 static nsecs_t sLastResyncAttempted = 0;
1320 const nsecs_t now = systemTime();
1321 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001322 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001323 }
Dan Stoza57164302017-05-08 14:03:54 -07001324 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001325}
1326
Steven Thomasb02664d2017-07-26 18:48:28 -07001327void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1328 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001329 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001330 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001331 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001332 return;
1333 }
1334
1335 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001336 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001337 return;
1338 }
1339
Jamie Gennisd1700752013-10-14 12:22:52 -07001340 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001341
Jamie Gennisd1700752013-10-14 12:22:52 -07001342 { // Scope for the lock
1343 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001344 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001345 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001346 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001347 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001348
1349 if (needsHwVsync) {
1350 enableHardwareVsync();
1351 } else {
1352 disableHardwareVsync(false);
1353 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001354}
1355
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001356void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001357 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1358 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001359}
1360
Lloyd Pique715a2c12017-12-14 17:18:08 -08001361void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1362 HWC2::Connection connection) {
1363 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1364 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001365
Lloyd Piqueba04e622017-12-14 17:11:26 -08001366 // Ignore events that do not have the right sequenceId.
1367 if (sequenceId != getBE().mComposerSequenceId) {
1368 return;
1369 }
1370
Steven Thomasb02664d2017-07-26 18:48:28 -07001371 // Only lock if we're not on the main thread. This function is normally
1372 // called on a hwbinder thread, but for the primary display it's called on
1373 // the main thread with the state lock already held, so don't attempt to
1374 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001375 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001376
Lloyd Pique715a2c12017-12-14 17:18:08 -08001377 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001378
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001379 if (std::this_thread::get_id() == mMainThreadId) {
1380 // Process all pending hot plug events immediately if we are on the main thread.
1381 processDisplayHotplugEventsLocked();
1382 }
1383
Lloyd Piqueba04e622017-12-14 17:11:26 -08001384 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001385}
1386
Steven Thomasb02664d2017-07-26 18:48:28 -07001387void SurfaceFlinger::onRefreshReceived(int sequenceId,
1388 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001389 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001390 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001391 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001392 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001393 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001394}
1395
Dan Stoza9e56aa02015-11-02 13:00:03 -08001396void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001397 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001398 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001399 getHwComposer().setVsyncEnabled(disp,
1400 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001401}
1402
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001403// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001404void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001405 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001406 // Clear the drawing state so that the logic inside of
1407 // handleTransactionLocked will fire. It will determine the delta between
1408 // mCurrentState and mDrawingState and re-apply all changes when we make the
1409 // transition.
1410 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001411 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001412 mDisplays.clear();
1413}
1414
Steven Thomas050b2c82017-03-06 11:45:16 -08001415void SurfaceFlinger::updateVrFlinger() {
1416 if (!mVrFlinger)
1417 return;
1418 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001419 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001420 return;
1421 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001422
David Sodman105b7dc2017-11-04 20:28:14 -07001423 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001424 ALOGE("Vr flinger is only supported for remote hardware composer"
1425 " service connections. Ignoring request to transition to vr"
1426 " flinger.");
1427 mVrFlingerRequestsDisplay = false;
1428 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001429 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001430
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001431 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001432
Steven Thomasb02664d2017-07-26 18:48:28 -07001433 int currentDisplayPowerMode = getDisplayDeviceLocked(
1434 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001435
Steven Thomasb02664d2017-07-26 18:48:28 -07001436 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001437 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001438 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001439
Steven Thomasb02664d2017-07-26 18:48:28 -07001440 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001441 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001442 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1443 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001444 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001445
David Sodman105b7dc2017-11-04 20:28:14 -07001446 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1447 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001448
1449 if (vrFlingerRequestsDisplay) {
1450 mVrFlinger->GrantDisplayOwnership();
1451 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001452 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001453 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001454
1455 mVisibleRegionsDirty = true;
1456 invalidateHwcGeometry();
1457
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001458 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001459 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1460 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1461 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001462
Steven Thomasb02664d2017-07-26 18:48:28 -07001463 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001464 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001465 const nsecs_t period = activeConfig->getVsyncPeriod();
1466 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001467
Steven Thomasb02664d2017-07-26 18:48:28 -07001468 // Use phase of 0 since phase is not known.
1469 // Use latency of 0, which will snap to the ideal latency.
1470 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001471
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001472 android_atomic_or(1, &mRepaintEverything);
1473 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001474}
1475
Mathias Agopian4fec8732012-06-29 14:12:52 -07001476void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001477 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001478 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001479 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001480 bool frameMissed = !mHadClientComposition &&
1481 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001482 (mPreviousPresentFence->getSignalTime() ==
1483 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001484 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001485 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001486 signalLayerUpdate();
1487 break;
1488 }
1489
Steven Thomas050b2c82017-03-06 11:45:16 -08001490 // Now that we're going to make it to the handleMessageTransaction()
1491 // call below it's safe to call updateVrFlinger(), which will
1492 // potentially trigger a display handoff.
1493 updateVrFlinger();
1494
Dan Stoza6b9454d2014-11-07 16:00:59 -08001495 bool refreshNeeded = handleMessageTransaction();
1496 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001497 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001498 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001499 // Signal a refresh if a transaction modified the window state,
1500 // a new buffer was latched, or if HWC has requested a full
1501 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001502 signalRefresh();
1503 }
1504 break;
1505 }
1506 case MessageQueue::REFRESH: {
1507 handleMessageRefresh();
1508 break;
1509 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001510 }
1511}
1512
Dan Stoza6b9454d2014-11-07 16:00:59 -08001513bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001514 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001515 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001516 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001517 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001518 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001519 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001520}
1521
Dan Stoza6b9454d2014-11-07 16:00:59 -08001522bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001523 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001524 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001525}
1526
1527void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001528 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001529
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001530 mRefreshPending = false;
1531
Pablo Ceballos40845df2016-01-25 17:41:15 -08001532 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001533
Brian Andersond6927fb2016-07-23 23:37:30 -07001534 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001535 rebuildLayerStacks();
1536 setUpHWComposer();
1537 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001538 doTracing("handleRefresh");
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001539 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001540 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001541 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001542
David Sodman105b7dc2017-11-04 20:28:14 -07001543 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001544
1545 mHadClientComposition = false;
1546 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1547 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1548 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001549 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001550 }
Dan Stoza2713c302018-03-28 17:07:36 -07001551 mVsyncModulator.setLastFrameUsedRenderEngine(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001552
Dan Stoza9e56aa02015-11-02 13:00:03 -08001553 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001554}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001555
Mathias Agopiancd60f992012-08-16 16:28:27 -07001556void SurfaceFlinger::doDebugFlashRegions()
1557{
1558 // is debugging enabled
1559 if (CC_LIKELY(!mDebugRegion))
1560 return;
1561
1562 const bool repaintEverything = mRepaintEverything;
1563 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1564 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001565 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001566 // transform the dirty region into this screen's coordinate space
1567 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1568 if (!dirtyRegion.isEmpty()) {
1569 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001570 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001571
1572 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001573 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001574 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001575 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1576
Mathias Agopianda27af92012-09-13 18:17:13 -07001577 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001578 }
1579 }
1580 }
1581
1582 postFramebuffer();
1583
1584 if (mDebugRegion > 1) {
1585 usleep(mDebugRegion * 1000);
1586 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001587
Dan Stoza9e56aa02015-11-02 13:00:03 -08001588 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001589 auto& displayDevice = mDisplays[displayId];
1590 if (!displayDevice->isDisplayOn()) {
1591 continue;
1592 }
1593
David Sodman105b7dc2017-11-04 20:28:14 -07001594 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1595 ALOGE_IF(result != NO_ERROR,
1596 "prepareFrame for display %zd failed:"
1597 " %d (%s)",
1598 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001599 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001600}
1601
Adrian Roos1e1a1282017-11-01 19:05:31 +01001602void SurfaceFlinger::doTracing(const char* where) {
1603 ATRACE_CALL();
1604 ATRACE_NAME(where);
1605 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001606 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001607 }
1608}
1609
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001610void SurfaceFlinger::logLayerStats() {
1611 ATRACE_CALL();
1612 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1613 int32_t hwcId = -1;
1614 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1615 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1616 if (displayDevice->isPrimary()) {
1617 hwcId = displayDevice->getHwcDisplayId();
1618 break;
1619 }
1620 }
1621 if (hwcId < 0) {
1622 ALOGE("LayerStats: Hmmm, no primary display?");
1623 return;
1624 }
1625 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1626 }
1627}
1628
Brian Andersond6927fb2016-07-23 23:37:30 -07001629void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001630{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001631 ATRACE_CALL();
1632 ALOGV("preComposition");
1633
Mathias Agopiancd60f992012-08-16 16:28:27 -07001634 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001635 mDrawingState.traverseInZOrder([&](Layer* layer) {
1636 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001637 needExtraInvalidate = true;
1638 }
Robert Carr2047fae2016-11-28 14:09:09 -08001639 });
1640
Mathias Agopiancd60f992012-08-16 16:28:27 -07001641 if (needExtraInvalidate) {
1642 signalLayerUpdate();
1643 }
1644}
1645
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001646void SurfaceFlinger::updateCompositorTiming(
1647 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1648 std::shared_ptr<FenceTime>& presentFenceTime) {
1649 // Update queue of past composite+present times and determine the
1650 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001651 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001652 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001653 while (!getBE().mCompositePresentTimes.empty()) {
1654 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001655 // Cached values should have been updated before calling this method,
1656 // which helps avoid duplicate syscalls.
1657 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1658 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1659 break;
1660 }
1661 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001662 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001663 }
1664
1665 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001666 while (getBE().mCompositePresentTimes.size() > 16) {
1667 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001668 }
1669
Brian Andersond0010582017-03-07 13:20:31 -08001670 setCompositorTimingSnapped(
1671 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1672}
1673
1674void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1675 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001676 // Integer division and modulo round toward 0 not -inf, so we need to
1677 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001678 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001679 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1680 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1681
Brian Andersond0010582017-03-07 13:20:31 -08001682 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1683 if (idealLatency <= 0) {
1684 idealLatency = vsyncInterval;
1685 }
1686
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001687 // Snap the latency to a value that removes scheduling jitter from the
1688 // composition and present times, which often have >1ms of jitter.
1689 // Reducing jitter is important if an app attempts to extrapolate
1690 // something (such as user input) to an accurate diasplay time.
1691 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1692 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001693 nsecs_t bias = vsyncInterval / 2;
1694 int64_t extraVsyncs =
1695 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1696 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1697 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001698
David Sodman99974d22017-11-28 12:04:33 -08001699 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1700 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1701 getBE().mCompositorTiming.interval = vsyncInterval;
1702 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001703}
1704
1705void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001706{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001707 ATRACE_CALL();
1708 ALOGV("postComposition");
1709
Brian Anderson3546a3f2016-07-14 11:51:14 -07001710 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001711 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001712 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001713 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001714 }
1715
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001716 // |mStateLock| not needed as we are on the main thread
1717 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001718
David Sodman73beded2017-11-15 11:56:06 -08001719 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001720 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001721 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001722 glCompositionDoneFenceTime =
1723 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001724 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001725 } else {
1726 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1727 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001728
David Sodman73beded2017-11-15 11:56:06 -08001729 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001730 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001731 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001732 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001733
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001734 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1735 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1736
1737 // We use the refreshStartTime which might be sampled a little later than
1738 // when we started doing work for this frame, but that should be okay
1739 // since updateCompositorTiming has snapping logic.
1740 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001741 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001742 CompositorTiming compositorTiming;
1743 {
David Sodman99974d22017-11-28 12:04:33 -08001744 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1745 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001746 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001747
Robert Carr2047fae2016-11-28 14:09:09 -08001748 mDrawingState.traverseInZOrder([&](Layer* layer) {
1749 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001750 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001751 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001752 recordBufferingStats(layer->getName().string(),
1753 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001754 }
Robert Carr2047fae2016-11-28 14:09:09 -08001755 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001756
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001757 if (presentFenceTime->isValid()) {
1758 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001759 enableHardwareVsync();
1760 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001761 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001762 }
1763 }
1764
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001765 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001766 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001767 enableHardwareVsync();
1768 }
1769 }
1770
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001771 if (mAnimCompositionPending) {
1772 mAnimCompositionPending = false;
1773
Brian Anderson4e606e32017-03-16 15:34:57 -07001774 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001775 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001776 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001777 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001778 // The HWC doesn't support present fences, so use the refresh
1779 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001780 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001781 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001782 mAnimFrameTracker.setActualPresentTime(presentTime);
1783 }
1784 mAnimFrameTracker.advanceFrame();
1785 }
Dan Stozab90cf072015-03-05 11:05:59 -08001786
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001787 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1788 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001789 return;
1790 }
1791
1792 nsecs_t currentTime = systemTime();
1793 if (mHasPoweredOff) {
1794 mHasPoweredOff = false;
1795 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001796 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001797 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001798 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1799 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001800 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001801 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001802 }
David Sodman4a36e932017-11-07 14:29:47 -08001803 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001804 }
David Sodman4a36e932017-11-07 14:29:47 -08001805 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001806}
1807
1808void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001809 ATRACE_CALL();
1810 ALOGV("rebuildLayerStacks");
1811
Mathias Agopiancd60f992012-08-16 16:28:27 -07001812 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001813 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001814 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001815 mVisibleRegionsDirty = false;
1816 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001817
Jeff Sharkey76488112017-02-27 14:15:18 -07001818 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1819 Region opaqueRegion;
1820 Region dirtyRegion;
1821 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001822 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001823 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1824 const Transform& tr(displayDevice->getTransform());
1825 const Rect bounds(displayDevice->getBounds());
1826 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001827 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001828
Jeff Sharkey76488112017-02-27 14:15:18 -07001829 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001830 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001831 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1832 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001833 Region drawRegion(tr.transform(
1834 layer->visibleNonTransparentRegion));
1835 drawRegion.andSelf(bounds);
1836 if (!drawRegion.isEmpty()) {
1837 layersSortedByZ.add(layer);
1838 } else {
1839 // Clear out the HWC layer if this layer was
1840 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001841 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001842 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001843 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001844 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001845 // WM changes displayDevice->layerStack upon sleep/awake.
1846 // Here we make sure we delete the HWC layers even if
1847 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001848 hwcLayerDestroyed = layer->destroyHwcLayer(
1849 displayDevice->getHwcDisplayId());
1850 }
1851
1852 // If a layer is not going to get a release fence because
1853 // it is invisible, but it is also going to release its
1854 // old buffer, add it to the list of layers needing
1855 // fences.
1856 if (hwcLayerDestroyed) {
1857 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1858 mLayersWithQueuedFrames.cend(), layer);
1859 if (found != mLayersWithQueuedFrames.cend()) {
1860 layersNeedingFences.add(layer);
1861 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001862 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001863 });
1864 }
1865 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001866 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001867 displayDevice->undefinedRegion.set(bounds);
1868 displayDevice->undefinedRegion.subtractSelf(
1869 tr.transform(opaqueRegion));
1870 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001871 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001872 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001873}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001874
Romain Guy0147a172017-06-01 13:53:56 -07001875mat4 SurfaceFlinger::computeSaturationMatrix() const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001876 if (mGlobalSaturationFactor == 1.0f) {
Romain Guy0147a172017-06-01 13:53:56 -07001877 return mat4();
1878 }
1879
1880 // Rec.709 luma coefficients
1881 float3 luminance{0.213f, 0.715f, 0.072f};
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001882 luminance *= 1.0f - mGlobalSaturationFactor;
Romain Guy0147a172017-06-01 13:53:56 -07001883 return mat4(
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001884 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
1885 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
1886 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
Romain Guy0147a172017-06-01 13:53:56 -07001887 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1888 );
1889}
1890
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001891// Returns a dataspace that fits all visible layers. The returned dataspace
1892// can only be one of
1893//
1894// - Dataspace::V0_SRGB
1895// - Dataspace::DISPLAY_P3
1896// - Dataspace::V0_SCRGB_LINEAR
1897// TODO(b/73825729) Add BT2020 data space.
1898ui::Dataspace SurfaceFlinger::getBestDataspace(
1899 const sp<const DisplayDevice>& displayDevice) const {
1900 Dataspace bestDataspace = Dataspace::V0_SRGB;
1901 for (const auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1902 switch (layer->getDataSpace()) {
1903 case Dataspace::V0_SCRGB:
1904 case Dataspace::V0_SCRGB_LINEAR:
1905 // return immediately
1906 return Dataspace::V0_SCRGB_LINEAR;
1907 case Dataspace::BT2020_PQ:
1908 case Dataspace::BT2020_ITU_PQ:
1909 // Historically, HDR dataspaces are ignored by SurfaceFlinger. But
1910 // since SurfaceFlinger simulates HDR support now, it should honor
1911 // them unless there is also native support.
Peiyong Lin62665892018-04-16 11:07:44 -07001912 if (!displayDevice->hasHDR10Support()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001913 return Dataspace::V0_SCRGB_LINEAR;
1914 }
1915 break;
1916 case Dataspace::DISPLAY_P3:
1917 bestDataspace = Dataspace::DISPLAY_P3;
1918 break;
1919 default:
1920 break;
1921 }
Romain Guy54f154a2017-10-24 21:40:32 +01001922 }
1923
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001924 return bestDataspace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001925}
1926
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001927// Pick the ColorMode / Dataspace for the display device.
1928// TODO(b/73825729) Add BT2020 color mode.
1929void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& displayDevice,
1930 ColorMode* outMode, Dataspace* outDataSpace) const {
1931 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1932 *outMode = ColorMode::NATIVE;
1933 *outDataSpace = Dataspace::UNKNOWN;
1934 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001935 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001936
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001937 switch (getBestDataspace(displayDevice)) {
1938 case Dataspace::DISPLAY_P3:
1939 case Dataspace::V0_SCRGB_LINEAR:
1940 *outMode = ColorMode::DISPLAY_P3;
1941 *outDataSpace = Dataspace::DISPLAY_P3;
1942 break;
1943 default:
1944 *outMode = ColorMode::SRGB;
1945 *outDataSpace = Dataspace::V0_SRGB;
1946 break;
1947 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001948}
1949
Mathias Agopiancd60f992012-08-16 16:28:27 -07001950void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001951 ATRACE_CALL();
1952 ALOGV("setUpHWComposer");
1953
Jesse Hall028dc8f2013-08-20 16:35:32 -07001954 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Dan Stozac7a25ad2018-04-12 11:45:09 -07001955 bool dirty = !mDisplays[dpy]->getDirtyRegion(mRepaintEverything).isEmpty();
Jesse Hallb7a05492014-08-14 15:45:06 -07001956 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1957 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1958
1959 // If nothing has changed (!dirty), don't recompose.
1960 // If something changed, but we don't currently have any visible layers,
1961 // and didn't when we last did a composition, then skip it this time.
1962 // The second rule does two things:
1963 // - When all layers are removed from a display, we'll emit one black
1964 // frame, then nothing more until we get new layers.
1965 // - When a display is created with a private layer stack, we won't
1966 // emit any black frames until a layer is added to the layer stack.
1967 bool mustRecompose = dirty && !(empty && wasEmpty);
1968
1969 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1970 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1971 mustRecompose ? "doing" : "skipping",
1972 dirty ? "+" : "-",
1973 empty ? "+" : "-",
1974 wasEmpty ? "+" : "-");
1975
Dan Stoza71433162014-02-04 16:22:36 -08001976 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001977
1978 if (mustRecompose) {
1979 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1980 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001981 }
1982
Dan Stoza9e56aa02015-11-02 13:00:03 -08001983 // build the h/w work list
1984 if (CC_UNLIKELY(mGeometryInvalid)) {
1985 mGeometryInvalid = false;
1986 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1987 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1988 const auto hwcId = displayDevice->getHwcDisplayId();
1989 if (hwcId >= 0) {
1990 const Vector<sp<Layer>>& currentLayers(
1991 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001992 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001993 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001994 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07001995 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001996 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001997 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001998 }
1999 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07002000
Robert Carrae060832016-11-28 10:51:00 -08002001 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002002 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002003 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07002004 }
2005 }
2006 }
2007 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002008 }
Riley Andrews03414a12014-07-01 14:22:59 -07002009
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002010
Romain Guy0147a172017-06-01 13:53:56 -07002011 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002012
Dan Stoza9e56aa02015-11-02 13:00:03 -08002013 // Set the per-frame data
2014 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2015 auto& displayDevice = mDisplays[displayId];
2016 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002017
Dan Stoza9e56aa02015-11-02 13:00:03 -08002018 if (hwcId < 0) {
2019 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07002020 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002021 if (colorMatrix != mPreviousColorMatrix) {
Yiwei Zhang7c64f172018-03-07 14:52:28 -08002022 displayDevice->setColorTransform(colorMatrix);
David Sodman105b7dc2017-11-04 20:28:14 -07002023 status_t result = getBE().mHwc->setColorTransform(hwcId, colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002024 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
2025 "display %zd: %d", displayId, result);
2026 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002027 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002028 if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2029 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Peiyong Lin62665892018-04-16 11:07:44 -07002030 !displayDevice->hasHDR10Support()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002031 layer->forceClientComposition(hwcId);
2032 }
2033
chaviwc9232ed2017-11-14 15:31:15 -08002034 if (layer->getForceClientComposition(hwcId)) {
2035 ALOGV("[%s] Requesting Client composition", layer->getName().string());
2036 layer->setCompositionType(hwcId, HWC2::Composition::Client);
2037 continue;
2038 }
2039
Dan Stoza9e56aa02015-11-02 13:00:03 -08002040 layer->setPerFrameData(displayDevice);
2041 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002042
2043 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002044 ColorMode colorMode;
2045 Dataspace dataSpace;
2046 pickColorMode(displayDevice, &colorMode, &dataSpace);
2047 setActiveColorModeInternal(displayDevice, colorMode, dataSpace);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002048 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002049 }
2050
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002051 mPreviousColorMatrix = colorMatrix;
2052
Dan Stoza9e56aa02015-11-02 13:00:03 -08002053 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002054 auto& displayDevice = mDisplays[displayId];
2055 if (!displayDevice->isDisplayOn()) {
2056 continue;
2057 }
2058
David Sodman105b7dc2017-11-04 20:28:14 -07002059 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002060 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2061 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002062 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002063}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002064
Mathias Agopiancd60f992012-08-16 16:28:27 -07002065void SurfaceFlinger::doComposition() {
2066 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002067 ALOGV("doComposition");
2068
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002069 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002070 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002071 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002072 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002073 // transform the dirty region into this screen's coordinate space
2074 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002075
2076 // repaint the framebuffer (if needed)
2077 doDisplayComposition(hw, dirtyRegion);
2078
Mathias Agopiancd60f992012-08-16 16:28:27 -07002079 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002080 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002081 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002082 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002083 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002084}
2085
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002086void SurfaceFlinger::postFramebuffer()
2087{
Mathias Agopian841cde52012-03-01 15:44:37 -08002088 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002089 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002090
Mathias Agopiana44b0412011-10-16 18:46:35 -07002091 const nsecs_t now = systemTime();
2092 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002093
Dan Stoza9e56aa02015-11-02 13:00:03 -08002094 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2095 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002096 if (!displayDevice->isDisplayOn()) {
2097 continue;
2098 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002099 const auto hwcId = displayDevice->getHwcDisplayId();
2100 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002101 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002102 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002103 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002104 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002105 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002106 // The layer buffer from the previous frame (if any) is released
2107 // by HWC only when the release fence from this frame (if any) is
2108 // signaled. Always get the release fence from HWC first.
2109 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002110 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002111
2112 // If the layer was client composited in the previous frame, we
2113 // need to merge with the previous client target acquire fence.
2114 // Since we do not track that, always merge with the current
2115 // client target acquire fence when it is available, even though
2116 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002117 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002118 releaseFence = Fence::merge("LayerRelease", releaseFence,
2119 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002120 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002121
Dan Stoza9e56aa02015-11-02 13:00:03 -08002122 layer->onLayerDisplayed(releaseFence);
2123 }
Chia-I Wu83806892017-11-16 10:50:20 -08002124
2125 // We've got a list of layers needing fences, that are disjoint with
2126 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2127 // supply them with the present fence.
2128 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002129 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002130 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2131 layer->onLayerDisplayed(presentFence);
2132 }
2133 }
2134
Dan Stoza9e56aa02015-11-02 13:00:03 -08002135 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002136 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002137 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002138 }
2139
Mathias Agopiana44b0412011-10-16 18:46:35 -07002140 mLastSwapBufferTime = systemTime() - now;
2141 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002142
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002143 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002144 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2145 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2146 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2147 logFrameStats();
2148 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002149 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002150}
2151
Mathias Agopian87baae12012-07-31 12:38:26 -07002152void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002153{
Mathias Agopian841cde52012-03-01 15:44:37 -08002154 ATRACE_CALL();
2155
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002156 // here we keep a copy of the drawing state (that is the state that's
2157 // going to be overwritten by handleTransactionLocked()) outside of
2158 // mStateLock so that the side-effects of the State assignment
2159 // don't happen with mStateLock held (which can cause deadlocks).
2160 State drawingState(mDrawingState);
2161
Mathias Agopianca4d3602011-05-19 15:38:14 -07002162 Mutex::Autolock _l(mStateLock);
2163 const nsecs_t now = systemTime();
2164 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002165
Mathias Agopianca4d3602011-05-19 15:38:14 -07002166 // Here we're guaranteed that some transaction flags are set
2167 // so we can call handleTransactionLocked() unconditionally.
2168 // We call getTransactionFlags(), which will also clear the flags,
2169 // with mStateLock held to guarantee that mCurrentState won't change
2170 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002171
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002172 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002173 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002174 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002175
Mathias Agopianca4d3602011-05-19 15:38:14 -07002176 mLastTransactionTime = systemTime() - now;
2177 mDebugInTransaction = 0;
2178 invalidateHwcGeometry();
2179 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002180}
2181
Lloyd Pique715a2c12017-12-14 17:18:08 -08002182DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique09594832018-01-22 17:48:03 -08002183 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002184 // Figure out whether the event is for the primary display or an
2185 // external display by matching the Hwc display id against one for a
2186 // connected display. If we did not find a match, we then check what
2187 // displays are not already connected to determine the type. If we don't
2188 // have a connected primary display, we assume the new display is meant to
2189 // be the primary display, and then if we don't have an external display,
2190 // we assume it is that.
2191 const auto primaryDisplayId =
2192 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2193 const auto externalDisplayId =
2194 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2195 if (primaryDisplayId && primaryDisplayId == display) {
2196 return DisplayDevice::DISPLAY_PRIMARY;
2197 } else if (externalDisplayId && externalDisplayId == display) {
2198 return DisplayDevice::DISPLAY_EXTERNAL;
2199 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2200 return DisplayDevice::DISPLAY_PRIMARY;
2201 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2202 return DisplayDevice::DISPLAY_EXTERNAL;
2203 }
2204
2205 return DisplayDevice::DISPLAY_ID_INVALID;
2206}
2207
Lloyd Piqueba04e622017-12-14 17:11:26 -08002208void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2209 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002210 auto displayType = determineDisplayType(event.display, event.connection);
2211 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2212 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2213 continue;
2214 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002215
2216 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2217 ALOGE("External displays are not supported by the vr hardware composer.");
2218 continue;
2219 }
2220
Lloyd Pique715a2c12017-12-14 17:18:08 -08002221 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002222
2223 if (event.connection == HWC2::Connection::Connected) {
Steven Thomas3bed0522018-03-20 15:40:48 -07002224 if (!mBuiltinDisplays[displayType].get()) {
2225 ALOGV("Creating built in display %d", displayType);
2226 mBuiltinDisplays[displayType] = new BBinder();
2227 // All non-virtual displays are currently considered secure.
2228 DisplayDeviceState info(displayType, true);
2229 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2230 "Built-in Screen" : "External Screen";
2231 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
Lloyd Pique4d234852018-01-22 17:21:36 -08002232 mInterceptor->saveDisplayCreation(info);
Steven Thomas3bed0522018-03-20 15:40:48 -07002233 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002234 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002235 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002236
Lloyd Piquefcd86612017-12-14 17:15:36 -08002237 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2238 if (idx >= 0) {
2239 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Lloyd Pique4d234852018-01-22 17:21:36 -08002240 mInterceptor->saveDisplayDeletion(info.displayId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002241 mCurrentState.displays.removeItemsAt(idx);
2242 }
2243 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002244 }
2245
2246 processDisplayChangesLocked();
2247 }
2248
2249 mPendingHotplugEvents.clear();
2250}
2251
Lloyd Pique09594832018-01-22 17:48:03 -08002252sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2253 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2254 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002255 bool hasWideColorGamut = false;
Lloyd Pique09594832018-01-22 17:48:03 -08002256 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002257 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Lloyd Pique09594832018-01-22 17:48:03 -08002258 for (ColorMode colorMode : modes) {
2259 switch (colorMode) {
2260 case ColorMode::DISPLAY_P3:
2261 case ColorMode::ADOBE_RGB:
2262 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002263 hasWideColorGamut = true;
Lloyd Pique09594832018-01-22 17:48:03 -08002264 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002265 // TODO(lpy) Handle BT2020, BT2100_PQ and BT2100_HLG properly.
Lloyd Pique09594832018-01-22 17:48:03 -08002266 default:
2267 break;
2268 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002269
2270 std::vector<RenderIntent> renderIntents = getHwComposer().getRenderIntents(hwcId,
2271 colorMode);
2272 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2273 for (auto intent : renderIntents) {
2274 if (intent == RenderIntent::ENHANCE) {
2275 mBuiltinDisplaySupportsEnhance = true;
2276 break;
2277 }
2278 }
2279 }
Lloyd Pique09594832018-01-22 17:48:03 -08002280 }
2281 }
2282
Peiyong Lin62665892018-04-16 11:07:44 -07002283 HdrCapabilities hdrCapabilities;
2284 getHwComposer().getHdrCapabilities(hwcId, &hdrCapabilities);
Lloyd Pique09594832018-01-22 17:48:03 -08002285
2286 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2287 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2288
2289 /*
2290 * Create our display's surface
2291 */
2292 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2293 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
2294 renderSurface->setAsync(state.type >= DisplayDevice::DISPLAY_VIRTUAL);
2295 renderSurface->setNativeWindow(nativeWindow.get());
2296 const int displayWidth = renderSurface->queryWidth();
2297 const int displayHeight = renderSurface->queryHeight();
2298
2299 // Make sure that composition can never be stalled by a virtual display
2300 // consumer that isn't processing buffers fast enough. We have to do this
2301 // in two places:
2302 // * Here, in case the display is composed entirely by HWC.
2303 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2304 // window's swap interval in eglMakeCurrent, so they'll override the
2305 // interval we set here.
2306 if (state.type >= DisplayDevice::DISPLAY_VIRTUAL) {
2307 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2308 }
2309
2310 // virtual displays are always considered enabled
2311 auto initialPowerMode = (state.type >= DisplayDevice::DISPLAY_VIRTUAL) ? HWC_POWER_MODE_NORMAL
2312 : HWC_POWER_MODE_OFF;
2313
2314 sp<DisplayDevice> hw =
2315 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2316 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
Peiyong Lin2c327ac2018-04-19 22:06:34 -07002317 hasWideColorGamut, hdrCapabilities,
2318 getHwComposer().getSupportedPerFrameMetadata(hwcId),
2319 initialPowerMode);
Lloyd Pique09594832018-01-22 17:48:03 -08002320
2321 if (maxFrameBufferAcquiredBuffers >= 3) {
2322 nativeWindowSurface->preallocateBuffers();
2323 }
2324
2325 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002326 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2327 if (hasWideColorGamut) {
Lloyd Pique09594832018-01-22 17:48:03 -08002328 defaultColorMode = ColorMode::SRGB;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002329 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique09594832018-01-22 17:48:03 -08002330 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002331 setActiveColorModeInternal(hw, defaultColorMode, defaultDataSpace);
Lloyd Pique09594832018-01-22 17:48:03 -08002332 hw->setLayerStack(state.layerStack);
2333 hw->setProjection(state.orientation, state.viewport, state.frame);
2334 hw->setDisplayName(state.displayName);
2335
2336 return hw;
2337}
2338
Lloyd Pique347200f2017-12-14 17:00:15 -08002339void SurfaceFlinger::processDisplayChangesLocked() {
2340 // here we take advantage of Vector's copy-on-write semantics to
2341 // improve performance by skipping the transaction entirely when
2342 // know that the lists are identical
2343 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2344 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2345 if (!curr.isIdenticalTo(draw)) {
2346 mVisibleRegionsDirty = true;
2347 const size_t cc = curr.size();
2348 size_t dc = draw.size();
2349
2350 // find the displays that were removed
2351 // (ie: in drawing state but not in current state)
2352 // also handle displays that changed
2353 // (ie: displays that are in both lists)
2354 for (size_t i = 0; i < dc;) {
2355 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2356 if (j < 0) {
2357 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002358 // Call makeCurrent() on the primary display so we can
2359 // be sure that nothing associated with this display
2360 // is current.
2361 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2362 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2363 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2364 if (hw != nullptr) hw->disconnect(getHwComposer());
2365 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2366 mEventThread->onHotplugReceived(draw[i].type, false);
2367 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002368 } else {
2369 // this display is in both lists. see if something changed.
2370 const DisplayDeviceState& state(curr[j]);
2371 const wp<IBinder>& display(curr.keyAt(j));
2372 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2373 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2374 if (state_binder != draw_binder) {
2375 // changing the surface is like destroying and
2376 // recreating the DisplayDevice, so we just remove it
2377 // from the drawing state, so that it get re-added
2378 // below.
2379 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2380 if (hw != nullptr) hw->disconnect(getHwComposer());
2381 mDisplays.removeItem(display);
2382 mDrawingState.displays.removeItemsAt(i);
2383 dc--;
2384 // at this point we must loop to the next item
2385 continue;
2386 }
2387
2388 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2389 if (disp != nullptr) {
2390 if (state.layerStack != draw[i].layerStack) {
2391 disp->setLayerStack(state.layerStack);
2392 }
2393 if ((state.orientation != draw[i].orientation) ||
2394 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2395 disp->setProjection(state.orientation, state.viewport, state.frame);
2396 }
2397 if (state.width != draw[i].width || state.height != draw[i].height) {
2398 disp->setDisplaySize(state.width, state.height);
2399 }
2400 }
2401 }
2402 ++i;
2403 }
2404
2405 // find displays that were added
2406 // (ie: in current state but not in drawing state)
2407 for (size_t i = 0; i < cc; i++) {
2408 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2409 const DisplayDeviceState& state(curr[i]);
2410
2411 sp<DisplaySurface> dispSurface;
2412 sp<IGraphicBufferProducer> producer;
2413 sp<IGraphicBufferProducer> bqProducer;
2414 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002415 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002416
2417 int32_t hwcId = -1;
2418 if (state.isVirtualDisplay()) {
2419 // Virtual displays without a surface are dormant:
2420 // they have external state (layer stack, projection,
2421 // etc.) but no internal state (i.e. a DisplayDevice).
2422 if (state.surface != nullptr) {
2423 // Allow VR composer to use virtual displays.
2424 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2425 int width = 0;
2426 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2427 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2428 int height = 0;
2429 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2430 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2431 int intFormat = 0;
2432 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2433 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002434 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002435
2436 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2437 }
2438
2439 // TODO: Plumb requested format back up to consumer
2440
2441 sp<VirtualDisplaySurface> vds =
2442 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2443 bqProducer, bqConsumer,
2444 state.displayName);
2445
2446 dispSurface = vds;
2447 producer = vds;
2448 }
2449 } else {
2450 ALOGE_IF(state.surface != nullptr,
2451 "adding a supported display, but rendering "
2452 "surface is provided (%p), ignoring it",
2453 state.surface.get());
2454
2455 hwcId = state.type;
2456 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2457 producer = bqProducer;
2458 }
2459
2460 const wp<IBinder>& display(curr.keyAt(i));
2461 if (dispSurface != nullptr) {
Lloyd Pique09594832018-01-22 17:48:03 -08002462 mDisplays.add(display,
2463 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2464 producer));
Lloyd Pique347200f2017-12-14 17:00:15 -08002465 if (!state.isVirtualDisplay()) {
2466 mEventThread->onHotplugReceived(state.type, true);
2467 }
2468 }
2469 }
2470 }
2471 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002472
2473 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002474}
2475
Mathias Agopian87baae12012-07-31 12:38:26 -07002476void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002477{
Dan Stoza7dde5992015-05-22 09:51:44 -07002478 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002479 mCurrentState.traverseInZOrder([](Layer* layer) {
2480 layer->notifyAvailableFrames();
2481 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002482
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002483 /*
2484 * Traversal of the children
2485 * (perform the transaction for each of them if needed)
2486 */
2487
Mathias Agopian3559b072012-08-15 13:46:03 -07002488 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002489 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002490 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002491 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002492
2493 const uint32_t flags = layer->doTransaction(0);
2494 if (flags & Layer::eVisibleRegion)
2495 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002496 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002497 }
2498
2499 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002500 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002501 */
2502
Mathias Agopiane57f2922012-08-09 16:29:12 -07002503 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002504 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002505 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002506 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002507
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002508 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002509 // The transform hint might have changed for some layers
2510 // (either because a display has changed, or because a layer
2511 // as changed).
2512 //
2513 // Walk through all the layers in currentLayers,
2514 // and update their transform hint.
2515 //
2516 // If a layer is visible only on a single display, then that
2517 // display is used to calculate the hint, otherwise we use the
2518 // default display.
2519 //
2520 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2521 // the hint is set before we acquire a buffer from the surface texture.
2522 //
2523 // NOTE: layer transactions have taken place already, so we use their
2524 // drawing state. However, SurfaceFlinger's own transaction has not
2525 // happened yet, so we must use the current state layer list
2526 // (soon to become the drawing state list).
2527 //
2528 sp<const DisplayDevice> disp;
2529 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002530 bool first = true;
2531 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002532 // NOTE: we rely on the fact that layers are sorted by
2533 // layerStack first (so we don't have to traverse the list
2534 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002535 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002536 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002537 currentlayerStack = layerStack;
2538 // figure out if this layerstack is mirrored
2539 // (more than one display) if so, pick the default display,
2540 // if not, pick the only display it's on.
2541 disp.clear();
2542 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2543 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002544 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002545 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002546 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002547 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002548 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002549 break;
2550 }
2551 }
2552 }
2553 }
Chet Haase91d25932013-04-11 15:24:55 -07002554
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002555 if (disp == nullptr) {
2556 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2557 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002558
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002559 // could be null when this layer is using a layerStack
2560 // that is not visible on any display. Also can occur at
2561 // screen off/on times.
2562 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002563 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002564
2565 // disp can be null if there is no display available at all to get
2566 // the transform hint from.
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002567 if (disp != nullptr) {
2568 layer->updateTransformHint(disp);
2569 }
Robert Carr2047fae2016-11-28 14:09:09 -08002570
2571 first = false;
2572 });
Mathias Agopian84300952012-11-21 16:02:13 -08002573 }
2574
2575
Mathias Agopian3559b072012-08-15 13:46:03 -07002576 /*
2577 * Perform our own transaction if needed
2578 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002579
2580 if (mLayersAdded) {
2581 mLayersAdded = false;
2582 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002583 mVisibleRegionsDirty = true;
2584 }
2585
2586 // some layers might have been removed, so
2587 // we need to update the regions they're exposing.
2588 if (mLayersRemoved) {
2589 mLayersRemoved = false;
2590 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002591 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002592 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002593 // this layer is not visible anymore
2594 // TODO: we could traverse the tree from front to back and
2595 // compute the actual visible region
2596 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002597 Region visibleReg;
2598 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002599 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002600 }
Robert Carr2047fae2016-11-28 14:09:09 -08002601 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002602 }
2603
2604 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002605
2606 updateCursorAsync();
2607}
2608
2609void SurfaceFlinger::updateCursorAsync()
2610{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002611 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2612 auto& displayDevice = mDisplays[displayId];
2613 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002614 continue;
2615 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002616
2617 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2618 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002619 }
2620 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002621}
2622
2623void SurfaceFlinger::commitTransaction()
2624{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002625 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002626 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002627 for (const auto& l : mLayersPendingRemoval) {
2628 recordBufferingStats(l->getName().string(),
2629 l->getOccupancyHistory(true));
2630 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002631 }
2632 mLayersPendingRemoval.clear();
2633 }
2634
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002635 // If this transaction is part of a window animation then the next frame
2636 // we composite should be considered an animation as well.
2637 mAnimCompositionPending = mAnimTransactionPending;
2638
Mathias Agopian4fec8732012-06-29 14:12:52 -07002639 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002640 mDrawingState.traverseInZOrder([](Layer* layer) {
2641 layer->commitChildList();
2642 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002643 mTransactionPending = false;
2644 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002645 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002646}
2647
Chia-I Wuab0c3192017-08-01 11:29:00 -07002648void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002649 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002650{
Mathias Agopian841cde52012-03-01 15:44:37 -08002651 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002652 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002653
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002654 Region aboveOpaqueLayers;
2655 Region aboveCoveredLayers;
2656 Region dirty;
2657
Mathias Agopian87baae12012-07-31 12:38:26 -07002658 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002659
Robert Carr2047fae2016-11-28 14:09:09 -08002660 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002661 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002662 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002663
Jesse Hall01e29052013-02-19 16:13:35 -08002664 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002665 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002666 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002667
Mathias Agopianab028732010-03-16 16:41:46 -07002668 /*
2669 * opaqueRegion: area of a surface that is fully opaque.
2670 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002671 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002672
2673 /*
2674 * visibleRegion: area of a surface that is visible on screen
2675 * and not fully transparent. This is essentially the layer's
2676 * footprint minus the opaque regions above it.
2677 * Areas covered by a translucent surface are considered visible.
2678 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002679 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002680
2681 /*
2682 * coveredRegion: area of a surface that is covered by all
2683 * visible regions above it (which includes the translucent areas).
2684 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002685 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002686
Jesse Halla8026d22012-09-25 13:25:04 -07002687 /*
2688 * transparentRegion: area of a surface that is hinted to be completely
2689 * transparent. This is only used to tell when the layer has no visible
2690 * non-transparent regions and can be removed from the layer list. It
2691 * does not affect the visibleRegion of this layer or any layers
2692 * beneath it. The hint may not be correct if apps don't respect the
2693 * SurfaceView restrictions (which, sadly, some don't).
2694 */
2695 Region transparentRegion;
2696
Mathias Agopianab028732010-03-16 16:41:46 -07002697
2698 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002699 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002700 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002701 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002702 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002703 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002704 if (!visibleRegion.isEmpty()) {
2705 // Remove the transparent area from the visible region
2706 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002707 if (tr.preserveRects()) {
2708 // transform the transparent region
2709 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002710 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002711 // transformation too complex, can't do the
2712 // transparent region optimization.
2713 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002714 }
Mathias Agopianab028732010-03-16 16:41:46 -07002715 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002716
Mathias Agopianab028732010-03-16 16:41:46 -07002717 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002718 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002719 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002720 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2721 // the opaque region is the layer's footprint
2722 opaqueRegion = visibleRegion;
2723 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002724 }
2725 }
2726
Robert Carre5f4f692018-01-12 13:12:28 -08002727 if (visibleRegion.isEmpty()) {
2728 layer->clearVisibilityRegions();
2729 return;
2730 }
2731
Mathias Agopianab028732010-03-16 16:41:46 -07002732 // Clip the covered region to the visible region
2733 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2734
2735 // Update aboveCoveredLayers for next (lower) layer
2736 aboveCoveredLayers.orSelf(visibleRegion);
2737
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002738 // subtract the opaque region covered by the layers above us
2739 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002740
2741 // compute this layer's dirty region
2742 if (layer->contentDirty) {
2743 // we need to invalidate the whole region
2744 dirty = visibleRegion;
2745 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002746 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002747 layer->contentDirty = false;
2748 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002749 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002750 * the exposed region consists of two components:
2751 * 1) what's VISIBLE now and was COVERED before
2752 * 2) what's EXPOSED now less what was EXPOSED before
2753 *
2754 * note that (1) is conservative, we start with the whole
2755 * visible region but only keep what used to be covered by
2756 * something -- which mean it may have been exposed.
2757 *
2758 * (2) handles areas that were not covered by anything but got
2759 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002760 */
Mathias Agopianab028732010-03-16 16:41:46 -07002761 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002762 const Region oldVisibleRegion = layer->visibleRegion;
2763 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002764 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2765 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002766 }
2767 dirty.subtractSelf(aboveOpaqueLayers);
2768
2769 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002770 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002771
Mathias Agopianab028732010-03-16 16:41:46 -07002772 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002773 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002774
Jesse Halla8026d22012-09-25 13:25:04 -07002775 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002776 layer->setVisibleRegion(visibleRegion);
2777 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002778 layer->setVisibleNonTransparentRegion(
2779 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002780 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002781
Mathias Agopian87baae12012-07-31 12:38:26 -07002782 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002783}
2784
Chia-I Wuab0c3192017-08-01 11:29:00 -07002785void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002786 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002787 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002788 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002789 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002790 }
2791 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002792}
2793
Dan Stoza6b9454d2014-11-07 16:00:59 -08002794bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002795{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002796 ALOGV("handlePageFlip");
2797
Brian Andersond6927fb2016-07-23 23:37:30 -07002798 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002799
Mathias Agopian4fec8732012-06-29 14:12:52 -07002800 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002801 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002802 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002803
2804 // Store the set of layers that need updates. This set must not change as
2805 // buffers are being latched, as this could result in a deadlock.
2806 // Example: Two producers share the same command stream and:
2807 // 1.) Layer 0 is latched
2808 // 2.) Layer 0 gets a new frame
2809 // 2.) Layer 1 gets a new frame
2810 // 3.) Layer 1 is latched.
2811 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2812 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002813 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002814 if (layer->hasQueuedFrame()) {
2815 frameQueued = true;
2816 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002817 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002818 } else {
2819 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002820 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002821 } else {
2822 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002823 }
Robert Carr2047fae2016-11-28 14:09:09 -08002824 });
2825
Dan Stoza9e56aa02015-11-02 13:00:03 -08002826 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002827 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002828 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002829 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002830 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002831 newDataLatched = true;
2832 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002833 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002834
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002835 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002836
2837 // If we will need to wake up at some time in the future to deal with a
2838 // queued frame that shouldn't be displayed during this vsync period, wake
2839 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002840 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002841 signalLayerUpdate();
2842 }
2843
2844 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002845 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002846}
2847
Mathias Agopianad456f92011-01-13 17:53:01 -08002848void SurfaceFlinger::invalidateHwcGeometry()
2849{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002850 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002851}
2852
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002853
Fabien Sanglard830b8472016-11-30 16:35:58 -08002854void SurfaceFlinger::doDisplayComposition(
2855 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002856 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002857{
Dan Stoza71433162014-02-04 16:22:36 -08002858 // We only need to actually compose the display if:
2859 // 1) It is being handled by hardware composer, which may need this to
2860 // keep its virtual display state machine in sync, or
2861 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002862 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002863 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002864 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002865 return;
2866 }
2867
Dan Stoza9e56aa02015-11-02 13:00:03 -08002868 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002869 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002870
2871 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002872 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002873}
2874
Chia-I Wub02087d2017-11-09 10:19:54 -08002875bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002876{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002877 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002878
Chia-I Wub02087d2017-11-09 10:19:54 -08002879 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002880 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002881 const auto hwcId = displayDevice->getHwcDisplayId();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002882 const bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
2883 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
2884 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2885 HWC2::Capability::SkipClientColorTransform);
2886 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002887
2888 mat4 oldColorMatrix;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002889 mat4 legacySrgbSaturationMatrix = mLegacySrgbSaturationMatrix;
2890 const bool applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002891 if (applyColorMatrix) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002892 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002893 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002894 legacySrgbSaturationMatrix = colorMatrix * legacySrgbSaturationMatrix;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002895 }
2896
Dan Stoza9e56aa02015-11-02 13:00:03 -08002897 if (hasClientComposition) {
2898 ALOGV("hasClientComposition");
2899
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002900 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002901 if (displayDevice->hasWideColorGamut()) {
2902 outputDataspace = displayDevice->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002903 }
2904 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
2905
Chia-I Wu7f402902017-11-09 12:51:10 -08002906 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002907 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002908 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002909 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002910
2911 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002912 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002913 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2914 }
2915 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002916 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002917
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002918 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002919 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002920 // when using overlays, we assume a fully transparent framebuffer
2921 // NOTE: we could reduce how much we need to clear, for instance
2922 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002923 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002924 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002925 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002926 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002927 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002928 // we're left with the letterbox region
2929 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002930 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002931
2932 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002933 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002934
Mathias Agopianb9494d52012-04-18 02:28:45 -07002935 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002936 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002937 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002938 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002939 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002940 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002941
Dan Stoza9e56aa02015-11-02 13:00:03 -08002942 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002943 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002944 // scissor on the main display. It should never be needed
2945 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002946 const Rect& bounds(displayDevice->getBounds());
2947 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002948 if (scissor != bounds) {
2949 // scissor doesn't match the screen's dimensions, so we
2950 // need to clear everything outside of it and enable
2951 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002952
Mathias Agopianf45c5102012-10-24 16:29:17 -07002953 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002954 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002955 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002956 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002957 }
2958 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002959 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002960
Mathias Agopian85d751c2012-08-29 16:59:24 -07002961 /*
2962 * and then, render the layers targeted at the framebuffer
2963 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002964
Dan Stoza9e56aa02015-11-02 13:00:03 -08002965 ALOGV("Rendering client layers");
2966 const Transform& displayTransform = displayDevice->getTransform();
2967 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002968 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002969 bool firstLayer = true;
2970 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002971 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002972 displayTransform.transform(layer->visibleRegion)));
2973 ALOGV("Layer: %s", layer->getName().string());
2974 ALOGV(" Composition type: %s",
2975 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002976 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002977 switch (layer->getCompositionType(hwcId)) {
2978 case HWC2::Composition::Cursor:
2979 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002980 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002981 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002982 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002983 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002984 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002985 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002986 // never clear the very first layer since we're
2987 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002988 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002989 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002990 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002991 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002992 case HWC2::Composition::Client: {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002993 // Only apply saturation matrix layer that is legacy SRGB dataspace
2994 // when auto color mode is on.
2995 bool restore = false;
2996 mat4 savedMatrix;
2997 if (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
2998 layer->isLegacySrgbDataSpace()) {
2999 savedMatrix =
3000 getRenderEngine().setupColorTransform(legacySrgbSaturationMatrix);
3001 restore = true;
3002 }
chaviwa76b2712017-09-20 12:02:26 -07003003 layer->draw(renderArea, clip);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003004 if (restore) {
3005 getRenderEngine().setupColorTransform(savedMatrix);
3006 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003007 break;
3008 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003009 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07003010 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003011 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003012 } else {
3013 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003014 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003015 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003016 }
3017 } else {
3018 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08003019 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08003020 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08003021 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07003022 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07003023 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07003024 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003025 }
3026 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003027
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003028 if (applyColorMatrix) {
3029 getRenderEngine().setupColorTransform(oldColorMatrix);
3030 }
3031
Mathias Agopianf45c5102012-10-24 16:29:17 -07003032 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003033 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003034 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003035}
3036
Fabien Sanglard830b8472016-11-30 16:35:58 -08003037void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
3038 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003039 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003040 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003041}
3042
Dan Stoza7d89d062015-04-30 13:29:25 -07003043status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003044 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003045 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003046 const sp<Layer>& lbc,
3047 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003048{
Dan Stoza7d89d062015-04-30 13:29:25 -07003049 // add this layer to the current state list
3050 {
3051 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003052 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003053 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3054 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003055 return NO_MEMORY;
3056 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003057 if (parent == nullptr) {
3058 mCurrentState.layersSortedByZ.add(lbc);
3059 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003060 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003061 ALOGE("addClientLayer called with a removed parent");
3062 return NAME_NOT_FOUND;
3063 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003064 parent->addChild(lbc);
3065 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003066
Dan Stoza101d8dc2018-02-27 15:42:25 -08003067 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
Dan Stoza0a0158c2018-03-16 13:38:54 -07003068 // TODO (b/74616334): Change this back to a fatal assert once the leak is fixed
3069 ALOGE_IF(mGraphicBufferProducerList.size() > mMaxGraphicBufferProducerListSize,
3070 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3071 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize,
3072 mNumLayers);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003073 mLayersAdded = true;
3074 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003075 }
3076
Mathias Agopian96f08192010-06-02 23:28:45 -07003077 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003078 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003079
Dan Stoza7d89d062015-04-30 13:29:25 -07003080 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003081}
3082
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003083status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003084 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003085 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3086}
Robert Carr7f9b8992017-03-10 11:08:39 -08003087
chaviwca27f252018-02-06 16:46:39 -08003088status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3089 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003090 if (layer->isPendingRemoval()) {
3091 return NO_ERROR;
3092 }
3093
Robert Carr1f0a16a2016-10-24 16:27:39 -07003094 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003095 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003096 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003097 if (topLevelOnly) {
3098 return NO_ERROR;
3099 }
3100
Chia-I Wu98f1c102017-05-30 14:54:08 -07003101 sp<Layer> ancestor = p;
3102 while (ancestor->getParent() != nullptr) {
3103 ancestor = ancestor->getParent();
3104 }
3105 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3106 ALOGE("removeLayer called with a layer whose parent has been removed");
3107 return NAME_NOT_FOUND;
3108 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003109
3110 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003111 } else {
3112 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003113 }
3114
Robert Carr136e2f62017-02-08 17:54:29 -08003115 // As a matter of normal operation, the LayerCleaner will produce a second
3116 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3117 // so we will succeed in promoting it, but it's already been removed
3118 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3119 // otherwise something has gone wrong and we are leaking the layer.
3120 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003121 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3122 layer->getName().string(),
3123 (p != nullptr) ? p->getName().string() : "no-parent");
3124 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003125 } else if (index < 0) {
3126 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003127 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003128
Chia-I Wuc6657022017-08-15 11:18:17 -07003129 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003130 mLayersPendingRemoval.add(layer);
3131 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003132 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003133 setTransactionFlags(eTransactionNeeded);
3134 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003135}
3136
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003137uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003138 return android_atomic_release_load(&mTransactionFlags);
3139}
3140
Mathias Agopian3f844832013-08-07 21:24:32 -07003141uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003142 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3143}
3144
Mathias Agopian3f844832013-08-07 21:24:32 -07003145uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza2713c302018-03-28 17:07:36 -07003146 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3147}
3148
3149uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3150 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003151 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza2713c302018-03-28 17:07:36 -07003152 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003153 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003154 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003155 }
3156 return old;
3157}
3158
chaviwca27f252018-02-06 16:46:39 -08003159bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3160 for (const ComposerState& state : states) {
3161 // Here we need to check that the interface we're given is indeed
3162 // one of our own. A malicious client could give us a nullptr
3163 // IInterface, or one of its own or even one of our own but a
3164 // different type. All these situations would cause us to crash.
3165 if (state.client == nullptr) {
3166 return true;
3167 }
3168
3169 sp<IBinder> binder = IInterface::asBinder(state.client);
3170 if (binder == nullptr) {
3171 return true;
3172 }
3173
3174 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3175 return true;
3176 }
3177 }
3178 return false;
3179}
3180
Mathias Agopian8b33f032012-07-24 20:43:54 -07003181void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003182 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003183 const Vector<DisplayState>& displays,
3184 uint32_t flags)
3185{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003186 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003187 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003188 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003189
chaviwca27f252018-02-06 16:46:39 -08003190 if (containsAnyInvalidClientState(states)) {
3191 return;
3192 }
3193
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003194 if (flags & eAnimation) {
3195 // For window updates that are part of an animation we must wait for
3196 // previous animation "frames" to be handled.
3197 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003198 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003199 if (CC_UNLIKELY(err != NO_ERROR)) {
3200 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003201 // caller after a few seconds.
3202 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3203 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003204 mAnimTransactionPending = false;
3205 break;
3206 }
3207 }
3208 }
3209
chaviwca27f252018-02-06 16:46:39 -08003210 for (const DisplayState& display : displays) {
3211 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003212 }
3213
chaviwca27f252018-02-06 16:46:39 -08003214 for (const ComposerState& state : states) {
3215 transactionFlags |= setClientStateLocked(state);
3216 }
3217
3218 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3219 // as destroyed should only occur after setting all other states. This is to allow for a
3220 // child re-parent to happen before marking its original parent as destroyed (which would
3221 // then mark the child as destroyed).
3222 for (const ComposerState& state : states) {
3223 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003224 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003225
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003226 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3227 // anyway. This can be used as a flush mechanism for previous async transactions.
3228 // Empty animation transaction can be used to simulate back-pressure, so also force a
3229 // transaction for empty animation transactions.
3230 if (transactionFlags == 0 &&
3231 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003232 transactionFlags = eTransactionNeeded;
3233 }
3234
Mathias Agopian386aa982011-11-07 21:58:03 -08003235 if (transactionFlags) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003236 if (mInterceptor->isEnabled()) {
3237 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003238 }
Irvel468051e2016-06-13 16:44:44 -07003239
Mathias Agopian386aa982011-11-07 21:58:03 -08003240 // this triggers the transaction
Dan Stoza2713c302018-03-28 17:07:36 -07003241 const auto start = (flags & eEarlyWakeup)
3242 ? VSyncModulator::TransactionStart::EARLY
3243 : VSyncModulator::TransactionStart::NORMAL;
3244 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003245
3246 // if this is a synchronous transaction, wait for it to take effect
3247 // before returning.
3248 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003249 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003250 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003251 if (flags & eAnimation) {
3252 mAnimTransactionPending = true;
3253 }
3254 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003255 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3256 if (CC_UNLIKELY(err != NO_ERROR)) {
3257 // just in case something goes wrong in SF, return to the
3258 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003259 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3260 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003261 break;
3262 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003263 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003264 }
3265}
3266
Mathias Agopiane57f2922012-08-09 16:29:12 -07003267uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3268{
Jesse Hall9a143922012-10-04 16:29:19 -07003269 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3270 if (dpyIdx < 0)
3271 return 0;
3272
Mathias Agopiane57f2922012-08-09 16:29:12 -07003273 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003274 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003275 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003276 const uint32_t what = s.what;
3277 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003278 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003279 disp.surface = s.surface;
3280 flags |= eDisplayTransactionNeeded;
3281 }
3282 }
3283 if (what & DisplayState::eLayerStackChanged) {
3284 if (disp.layerStack != s.layerStack) {
3285 disp.layerStack = s.layerStack;
3286 flags |= eDisplayTransactionNeeded;
3287 }
3288 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003289 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003290 if (disp.orientation != s.orientation) {
3291 disp.orientation = s.orientation;
3292 flags |= eDisplayTransactionNeeded;
3293 }
3294 if (disp.frame != s.frame) {
3295 disp.frame = s.frame;
3296 flags |= eDisplayTransactionNeeded;
3297 }
3298 if (disp.viewport != s.viewport) {
3299 disp.viewport = s.viewport;
3300 flags |= eDisplayTransactionNeeded;
3301 }
3302 }
Michael Lentine47e45402014-07-18 15:34:25 -07003303 if (what & DisplayState::eDisplaySizeChanged) {
3304 if (disp.width != s.width) {
3305 disp.width = s.width;
3306 flags |= eDisplayTransactionNeeded;
3307 }
3308 if (disp.height != s.height) {
3309 disp.height = s.height;
3310 flags |= eDisplayTransactionNeeded;
3311 }
3312 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003313 }
3314 return flags;
3315}
3316
chaviwca27f252018-02-06 16:46:39 -08003317uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3318 const layer_state_t& s = composerState.state;
3319 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3320
Mathias Agopian13127d82013-03-05 17:47:11 -08003321 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003322 if (layer == nullptr) {
3323 return 0;
3324 }
3325
3326 if (layer->isPendingRemoval()) {
3327 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3328 return 0;
3329 }
3330
3331 uint32_t flags = 0;
3332
3333 const uint32_t what = s.what;
3334 bool geometryAppliesWithResize =
3335 what & layer_state_t::eGeometryAppliesWithResize;
3336 if (what & layer_state_t::ePositionChanged) {
3337 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3338 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003339 }
chaviw8b3871a2017-11-01 17:41:01 -07003340 }
3341 if (what & layer_state_t::eLayerChanged) {
3342 // NOTE: index needs to be calculated before we update the state
3343 const auto& p = layer->getParent();
3344 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003345 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003346 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003347 mCurrentState.layersSortedByZ.removeAt(idx);
3348 mCurrentState.layersSortedByZ.add(layer);
3349 // we need traversal (state changed)
3350 // AND transaction (list changed)
3351 flags |= eTransactionNeeded|eTraversalNeeded;
3352 }
chaviw8b3871a2017-11-01 17:41:01 -07003353 } else {
3354 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003355 flags |= eTransactionNeeded|eTraversalNeeded;
3356 }
3357 }
chaviw8b3871a2017-11-01 17:41:01 -07003358 }
3359 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003360 // NOTE: index needs to be calculated before we update the state
3361 const auto& p = layer->getParent();
3362 if (p == nullptr) {
3363 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3364 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3365 mCurrentState.layersSortedByZ.removeAt(idx);
3366 mCurrentState.layersSortedByZ.add(layer);
3367 // we need traversal (state changed)
3368 // AND transaction (list changed)
3369 flags |= eTransactionNeeded|eTraversalNeeded;
3370 }
3371 } else {
3372 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3373 flags |= eTransactionNeeded|eTraversalNeeded;
3374 }
chaviw8b3871a2017-11-01 17:41:01 -07003375 }
3376 }
3377 if (what & layer_state_t::eSizeChanged) {
3378 if (layer->setSize(s.w, s.h)) {
3379 flags |= eTraversalNeeded;
3380 }
3381 }
3382 if (what & layer_state_t::eAlphaChanged) {
3383 if (layer->setAlpha(s.alpha))
3384 flags |= eTraversalNeeded;
3385 }
3386 if (what & layer_state_t::eColorChanged) {
3387 if (layer->setColor(s.color))
3388 flags |= eTraversalNeeded;
3389 }
3390 if (what & layer_state_t::eMatrixChanged) {
3391 if (layer->setMatrix(s.matrix))
3392 flags |= eTraversalNeeded;
3393 }
3394 if (what & layer_state_t::eTransparentRegionChanged) {
3395 if (layer->setTransparentRegionHint(s.transparentRegion))
3396 flags |= eTraversalNeeded;
3397 }
3398 if (what & layer_state_t::eFlagsChanged) {
3399 if (layer->setFlags(s.flags, s.mask))
3400 flags |= eTraversalNeeded;
3401 }
3402 if (what & layer_state_t::eCropChanged) {
3403 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3404 flags |= eTraversalNeeded;
3405 }
3406 if (what & layer_state_t::eFinalCropChanged) {
3407 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3408 flags |= eTraversalNeeded;
3409 }
3410 if (what & layer_state_t::eLayerStackChanged) {
3411 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3412 // We only allow setting layer stacks for top level layers,
3413 // everything else inherits layer stack from its parent.
3414 if (layer->hasParent()) {
3415 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3416 layer->getName().string());
3417 } else if (idx < 0) {
3418 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3419 "that also does not appear in the top level layer list. Something"
3420 " has gone wrong.", layer->getName().string());
3421 } else if (layer->setLayerStack(s.layerStack)) {
3422 mCurrentState.layersSortedByZ.removeAt(idx);
3423 mCurrentState.layersSortedByZ.add(layer);
3424 // we need traversal (state changed)
3425 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003426 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003427 }
3428 }
3429 if (what & layer_state_t::eDeferTransaction) {
3430 if (s.barrierHandle != nullptr) {
3431 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3432 } else if (s.barrierGbp != nullptr) {
3433 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3434 if (authenticateSurfaceTextureLocked(gbp)) {
3435 const auto& otherLayer =
3436 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3437 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3438 } else {
3439 ALOGE("Attempt to defer transaction to to an"
3440 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003441 }
3442 }
chaviw8b3871a2017-11-01 17:41:01 -07003443 // We don't trigger a traversal here because if no other state is
3444 // changed, we don't want this to cause any more work
3445 }
3446 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003447 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003448 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003449 if (!hadParent) {
3450 mCurrentState.layersSortedByZ.remove(layer);
3451 }
chaviw8b3871a2017-11-01 17:41:01 -07003452 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003453 }
chaviw8b3871a2017-11-01 17:41:01 -07003454 }
3455 if (what & layer_state_t::eReparentChildren) {
3456 if (layer->reparentChildren(s.reparentHandle)) {
3457 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003458 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003459 }
chaviw8b3871a2017-11-01 17:41:01 -07003460 if (what & layer_state_t::eDetachChildren) {
3461 layer->detachChildren();
3462 }
3463 if (what & layer_state_t::eOverrideScalingModeChanged) {
3464 layer->setOverrideScalingMode(s.overrideScalingMode);
3465 // We don't trigger a traversal here because if no other state is
3466 // changed, we don't want this to cause any more work
3467 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003468 return flags;
3469}
3470
chaviwca27f252018-02-06 16:46:39 -08003471void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3472 const layer_state_t& state = composerState.state;
3473 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3474
3475 sp<Layer> layer(client->getLayerUser(state.surface));
3476 if (layer == nullptr) {
3477 return;
3478 }
3479
3480 if (layer->isPendingRemoval()) {
3481 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3482 return;
3483 }
3484
3485 if (state.what & layer_state_t::eDestroySurface) {
3486 removeLayerLocked(mStateLock, layer);
3487 }
3488}
3489
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003490status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003491 const String8& name,
3492 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003493 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliuccd34842018-03-14 12:26:23 -07003494 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003495 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003496{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003497 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003498 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003499 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003500 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003501 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003502
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003503 status_t result = NO_ERROR;
3504
3505 sp<Layer> layer;
3506
Cody Northropbc755282017-03-31 12:00:08 -06003507 String8 uniqueName = getUniqueLayerName(name);
3508
Mathias Agopian3165cc22012-08-08 19:42:09 -07003509 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3510 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003511 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003512 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003513 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003514
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003515 break;
chaviw13fdc492017-06-27 12:40:18 -07003516 case ISurfaceComposerClient::eFXSurfaceColor:
3517 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003518 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003519 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003520 break;
3521 default:
3522 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003523 break;
3524 }
3525
Dan Stoza7d89d062015-04-30 13:29:25 -07003526 if (result != NO_ERROR) {
3527 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003528 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003529
Chia-I Wuab0c3192017-08-01 11:29:00 -07003530 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3531 // TODO b/64227542
3532 if (windowType == 441731) {
3533 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3534 layer->setPrimaryDisplayOnly();
3535 }
3536
Albert Chaulk479c60c2017-01-27 14:21:34 -05003537 layer->setInfo(windowType, ownerUid);
3538
Robert Carr1f0a16a2016-10-24 16:27:39 -07003539 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003540 if (result != NO_ERROR) {
3541 return result;
3542 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003543 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003544
3545 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003546 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003547}
3548
Cody Northropbc755282017-03-31 12:00:08 -06003549String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3550{
3551 bool matchFound = true;
3552 uint32_t dupeCounter = 0;
3553
3554 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3555 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3556
3557 // Loop over layers until we're sure there is no matching name
3558 while (matchFound) {
3559 matchFound = false;
3560 mDrawingState.traverseInZOrder([&](Layer* layer) {
3561 if (layer->getName() == uniqueName) {
3562 matchFound = true;
3563 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3564 }
3565 });
3566 }
3567
3568 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3569
3570 return uniqueName;
3571}
3572
David Sodman0c69cad2017-08-21 12:12:51 -07003573status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003574 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3575 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003576{
3577 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003578 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003579 case PIXEL_FORMAT_TRANSPARENT:
3580 case PIXEL_FORMAT_TRANSLUCENT:
3581 format = PIXEL_FORMAT_RGBA_8888;
3582 break;
3583 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003584 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003585 break;
3586 }
3587
David Sodman0c69cad2017-08-21 12:12:51 -07003588 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3589 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003590 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003591 *handle = layer->getHandle();
3592 *gbp = layer->getProducer();
3593 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003594 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003595
David Sodman0c69cad2017-08-21 12:12:51 -07003596 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003597 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003598}
3599
chaviw13fdc492017-06-27 12:40:18 -07003600status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003601 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003602 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003603{
chaviw13fdc492017-06-27 12:40:18 -07003604 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003605 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003606 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003607}
3608
Mathias Agopianac9fa422013-02-11 16:40:36 -08003609status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003610{
Robert Carr9524cb32017-02-13 11:32:32 -08003611 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003612 status_t err = NO_ERROR;
3613 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003614 if (l != nullptr) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003615 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003616 err = removeLayer(l);
3617 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3618 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003619 }
3620 return err;
3621}
3622
Mathias Agopian13127d82013-03-05 17:47:11 -08003623status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003624{
Mathias Agopian67106042013-03-14 19:18:13 -07003625 // called by ~LayerCleaner() when all references to the IBinder (handle)
3626 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003627 sp<Layer> l = layer.promote();
3628 if (l == nullptr) {
3629 // The layer has already been removed, carry on
3630 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003631 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003632 // If we have a parent, then we can continue to live as long as it does.
3633 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003634}
3635
Mathias Agopianb60314a2012-04-10 22:09:54 -07003636// ---------------------------------------------------------------------------
3637
Andy McFadden13a082e2012-08-24 10:16:42 -07003638void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003639 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003640 Vector<ComposerState> state;
3641 Vector<DisplayState> displays;
3642 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003643 d.what = DisplayState::eDisplayProjectionChanged |
3644 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003645 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003646 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003647 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003648 d.frame.makeInvalid();
3649 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003650 d.width = 0;
3651 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003652 displays.add(d);
3653 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003654 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3655 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003656
David Sodman105b7dc2017-11-04 20:28:14 -07003657 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003658 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003659 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003660
Brian Andersond0010582017-03-07 13:20:31 -08003661 // Use phase of 0 since phase is not known.
3662 // Use latency of 0, which will snap to the ideal latency.
3663 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003664}
3665
3666void SurfaceFlinger::initializeDisplays() {
3667 class MessageScreenInitialized : public MessageBase {
3668 SurfaceFlinger* flinger;
3669 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003670 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003671 virtual bool handler() {
3672 flinger->onInitializeDisplays();
3673 return true;
3674 }
3675 };
3676 sp<MessageBase> msg = new MessageScreenInitialized(this);
3677 postMessageAsync(msg); // we may be called from main thread, use async message
3678}
3679
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003680void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003681 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003682 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3683 this);
3684 int32_t type = hw->getDisplayType();
3685 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003686
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003687 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003688 return;
3689 }
3690
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003691 hw->setPowerMode(mode);
3692 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3693 ALOGW("Trying to set power mode for virtual display");
3694 return;
3695 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003696
Lloyd Pique4d234852018-01-22 17:21:36 -08003697 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003698 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003699 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3700 if (idx < 0) {
3701 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3702 return;
3703 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003704 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003705 }
3706
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003707 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003708 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003709 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003710 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3711 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003712 // FIXME: eventthread only knows about the main display right now
3713 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003714 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003715 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003716
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003717 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003718 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003719 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003720
3721 struct sched_param param = {0};
3722 param.sched_priority = 1;
3723 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3724 ALOGW("Couldn't set SCHED_FIFO on display on");
3725 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003726 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003727 // Turn off the display
3728 struct sched_param param = {0};
3729 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3730 ALOGW("Couldn't set SCHED_OTHER on display off");
3731 }
3732
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003733 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3734 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003735 disableHardwareVsync(true); // also cancels any in-progress resync
3736
Mathias Agopiancde87a32012-09-13 14:09:01 -07003737 // FIXME: eventthread only knows about the main display right now
3738 mEventThread->onScreenReleased();
3739 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003740
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003741 getHwComposer().setPowerMode(type, mode);
3742 mVisibleRegionsDirty = true;
3743 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003744 } else if (mode == HWC_POWER_MODE_DOZE ||
3745 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003746 // Update display while dozing
3747 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003748 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3749 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003750 // FIXME: eventthread only knows about the main display right now
3751 mEventThread->onScreenAcquired();
3752 resyncToHardwareVsync(true);
3753 }
3754 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3755 // Leave display going to doze
3756 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3757 disableHardwareVsync(true); // also cancels any in-progress resync
3758 // FIXME: eventthread only knows about the main display right now
3759 mEventThread->onScreenReleased();
3760 }
3761 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003762 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003763 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003764 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003765 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003766 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003767}
3768
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003769void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3770 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003771 SurfaceFlinger& mFlinger;
3772 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003773 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003774 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003775 MessageSetPowerMode(SurfaceFlinger& flinger,
3776 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3777 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003778 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003779 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003780 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003781 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003782 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003783 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003784 ALOGW("Attempt to set power mode = %d for virtual display",
3785 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003786 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003787 mFlinger.setPowerModeInternal(
3788 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003789 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003790 return true;
3791 }
3792 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003793 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003794 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003795}
3796
3797// ---------------------------------------------------------------------------
3798
Lloyd Pique755e3192018-01-31 16:46:15 -08003799status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3800 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003801 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003802
Mathias Agopianbd115332013-04-18 16:41:04 -07003803 IPCThreadState* ipc = IPCThreadState::self();
3804 const int pid = ipc->getCallingPid();
3805 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003806
Mathias Agopianbd115332013-04-18 16:41:04 -07003807 if ((uid != AID_SHELL) &&
3808 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003809 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003810 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003811 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003812 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003813 // (this would indicate SF is stuck, but we want to be able to
3814 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003815 status_t err = mStateLock.timedLock(s2ns(1));
3816 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003817 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003818 result.appendFormat(
3819 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3820 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003821 }
3822
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003823 bool dumpAll = true;
3824 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003825 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003826
3827 if (asProto) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003828 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviwa3d7bd32017-11-03 09:41:53 -07003829 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3830 dumpAll = false;
3831 }
3832
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003833 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003834 if ((index < numArgs) &&
3835 (args[index] == String16("--list"))) {
3836 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003837 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003838 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003839 }
3840
3841 if ((index < numArgs) &&
3842 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003843 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003844 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003845 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003846 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003847
3848 if ((index < numArgs) &&
3849 (args[index] == String16("--latency-clear"))) {
3850 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003851 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003852 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003853 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003854
3855 if ((index < numArgs) &&
3856 (args[index] == String16("--dispsync"))) {
3857 index++;
3858 mPrimaryDispSync.dump(result);
3859 dumpAll = false;
3860 }
Dan Stozab90cf072015-03-05 11:05:59 -08003861
3862 if ((index < numArgs) &&
3863 (args[index] == String16("--static-screen"))) {
3864 index++;
3865 dumpStaticScreenStats(result);
3866 dumpAll = false;
3867 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003868
3869 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003870 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003871 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003872 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003873 dumpAll = false;
3874 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003875
3876 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3877 index++;
3878 dumpWideColorInfo(result);
3879 dumpAll = false;
3880 }
Yiwei Zhang068e31b2018-02-21 13:02:45 -08003881
3882 if ((index < numArgs) &&
3883 (args[index] == String16("--enable-layer-stats"))) {
3884 index++;
3885 mLayerStats.enable();
3886 dumpAll = false;
3887 }
3888
3889 if ((index < numArgs) &&
3890 (args[index] == String16("--disable-layer-stats"))) {
3891 index++;
3892 mLayerStats.disable();
3893 dumpAll = false;
3894 }
3895
3896 if ((index < numArgs) &&
3897 (args[index] == String16("--clear-layer-stats"))) {
3898 index++;
3899 mLayerStats.clear();
3900 dumpAll = false;
3901 }
3902
3903 if ((index < numArgs) &&
3904 (args[index] == String16("--dump-layer-stats"))) {
3905 index++;
3906 mLayerStats.dump(result);
3907 dumpAll = false;
3908 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003909 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003910
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003911 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003912 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003913 }
3914
Mathias Agopian9795c422009-08-26 16:36:26 -07003915 if (locked) {
3916 mStateLock.unlock();
3917 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003918 }
3919 write(fd, result.string(), result.size());
3920 return NO_ERROR;
3921}
3922
Dan Stozac7014012014-02-14 15:03:43 -08003923void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3924 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003925{
Robert Carr2047fae2016-11-28 14:09:09 -08003926 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003927 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003928 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003929}
3930
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003931void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003932 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003933{
3934 String8 name;
3935 if (index < args.size()) {
3936 name = String8(args[index]);
3937 index++;
3938 }
3939
David Sodman105b7dc2017-11-04 20:28:14 -07003940 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003941 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003942 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003943
3944 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003945 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003946 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003947 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003948 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003949 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003950 }
Robert Carr2047fae2016-11-28 14:09:09 -08003951 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003952 }
3953}
3954
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003955void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003956 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003957{
3958 String8 name;
3959 if (index < args.size()) {
3960 name = String8(args[index]);
3961 index++;
3962 }
3963
Robert Carr2047fae2016-11-28 14:09:09 -08003964 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003965 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003966 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003967 }
Robert Carr2047fae2016-11-28 14:09:09 -08003968 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003969
Svetoslavd85084b2014-03-20 10:28:31 -07003970 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003971}
3972
Jamie Gennis6547ff42013-07-16 20:12:42 -07003973// This should only be called from the main thread. Otherwise it would need
3974// the lock and should use mCurrentState rather than mDrawingState.
3975void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003976 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003977 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003978 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003979
3980 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3981}
3982
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003983void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003984{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003985 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003986
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003987 if (isLayerTripleBufferingDisabled())
3988 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003989
3990 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003991 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003992 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003993 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003994 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3995 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003996 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003997}
3998
Dan Stozab90cf072015-03-05 11:05:59 -08003999void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4000{
4001 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004002 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4003 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004004 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004005 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004006 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4007 b + 1, bucketTimeSec, percent);
4008 }
David Sodman4a36e932017-11-07 14:29:47 -08004009 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004010 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004011 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004012 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004013 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004014}
4015
Dan Stozae77c7662016-05-13 11:37:28 -07004016void SurfaceFlinger::recordBufferingStats(const char* layerName,
4017 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004018 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4019 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004020 for (const auto& segment : history) {
4021 if (!segment.usedThirdBuffer) {
4022 stats.twoBufferTime += segment.totalTime;
4023 }
4024 if (segment.occupancyAverage < 1.0f) {
4025 stats.doubleBufferedTime += segment.totalTime;
4026 } else if (segment.occupancyAverage < 2.0f) {
4027 stats.tripleBufferedTime += segment.totalTime;
4028 }
4029 ++stats.numSegments;
4030 stats.totalTime += segment.totalTime;
4031 }
4032}
4033
Brian Andersond6927fb2016-07-23 23:37:30 -07004034void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4035 result.appendFormat("Layer frame timestamps:\n");
4036
4037 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4038 const size_t count = currentLayers.size();
4039 for (size_t i=0 ; i<count ; i++) {
4040 currentLayers[i]->dumpFrameEvents(result);
4041 }
4042}
4043
Dan Stozae77c7662016-05-13 11:37:28 -07004044void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4045 result.append("Buffering stats:\n");
4046 result.append(" [Layer name] <Active time> <Two buffer> "
4047 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004048 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004049 typedef std::tuple<std::string, float, float, float> BufferTuple;
4050 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004051 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004052 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004053 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004054 if (stats.numSegments == 0) {
4055 continue;
4056 }
4057 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4058 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4059 stats.totalTime;
4060 float doubleBufferRatio = static_cast<float>(
4061 stats.doubleBufferedTime) / stats.totalTime;
4062 float tripleBufferRatio = static_cast<float>(
4063 stats.tripleBufferedTime) / stats.totalTime;
4064 sorted.insert({activeTime, {name, twoBufferRatio,
4065 doubleBufferRatio, tripleBufferRatio}});
4066 }
4067 for (const auto& sortedPair : sorted) {
4068 float activeTime = sortedPair.first;
4069 const BufferTuple& values = sortedPair.second;
4070 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4071 std::get<0>(values).c_str(), activeTime,
4072 std::get<1>(values), std::get<2>(values),
4073 std::get<3>(values));
4074 }
4075 result.append("\n");
4076}
4077
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004078void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4079 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004080 result.appendFormat("DisplayColorSetting: %d\n", mDisplayColorSetting);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004081
4082 // TODO: print out if wide-color mode is active or not
4083
4084 for (size_t d = 0; d < mDisplays.size(); d++) {
4085 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4086 int32_t hwcId = displayDevice->getHwcDisplayId();
4087 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4088 continue;
4089 }
4090
4091 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004092 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004093 for (auto&& mode : modes) {
4094 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4095 }
4096
Peiyong Lina52f0292018-03-14 17:26:31 -07004097 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004098 result.appendFormat(" Current color mode: %s (%d)\n",
4099 decodeColorMode(currentMode).c_str(), currentMode);
4100 }
4101 result.append("\n");
4102}
4103
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004104LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004105 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004106 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4107 const State& state = useDrawing ? mDrawingState : mCurrentState;
4108 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004109 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004110 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004111 });
4112
4113 return layersProto;
4114}
4115
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004116LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4117 LayersProto layersProto;
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004118 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004119
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004120 SizeProto* resolution = layersProto.mutable_resolution();
4121 resolution->set_w(displayDevice->getWidth());
4122 resolution->set_h(displayDevice->getHeight());
4123
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004124 layersProto.set_color_mode(decodeColorMode(displayDevice->getActiveColorMode()));
4125 layersProto.set_color_transform(decodeColorTransform(displayDevice->getColorTransform()));
4126 layersProto.set_global_transform(
4127 static_cast<int32_t>(displayDevice->getOrientationTransform()));
4128
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004129 mDrawingState.traverseInZOrder([&](Layer* layer) {
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004130 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004131 LayerProto* layerProto = layersProto.add_layers();
4132 layer->writeToProto(layerProto, hwcId);
4133 }
4134 });
4135
4136 return layersProto;
4137}
4138
Mathias Agopian74d211a2013-04-22 16:55:35 +02004139void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4140 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004141{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004142 bool colorize = false;
4143 if (index < args.size()
4144 && (args[index] == String16("--color"))) {
4145 colorize = true;
4146 index++;
4147 }
4148
4149 Colorizer colorizer(colorize);
4150
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004151 // figure out if we're stuck somewhere
4152 const nsecs_t now = systemTime();
4153 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4154 const nsecs_t inTransaction(mDebugInTransaction);
4155 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4156 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4157
4158 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004159 * Dump library configuration.
4160 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004161
4162 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004163 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004164 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004165 appendSfConfigString(result);
4166 appendUiConfigString(result);
4167 appendGuiConfigString(result);
4168 result.append("\n");
4169
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004170 result.append("\nWide-Color information:\n");
4171 dumpWideColorInfo(result);
4172
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004173 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004174 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004175 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004176 result.append(SyncFeatures::getInstance().toString());
4177 result.append("\n");
4178
David Sodman105b7dc2017-11-04 20:28:14 -07004179 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004180
Andy McFadden41d67d72014-04-25 16:58:34 -07004181 colorizer.bold(result);
4182 result.append("DispSync configuration: ");
4183 colorizer.reset(result);
Dan Stoza2713c302018-03-28 17:07:36 -07004184 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, early sf phase %" PRId64
4185 " ns, present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4186 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, mVsyncModulator.getEarlyPhaseOffset(),
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004187 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004188 result.append("\n");
4189
Dan Stozab90cf072015-03-05 11:05:59 -08004190 // Dump static screen stats
4191 result.append("\n");
4192 dumpStaticScreenStats(result);
4193 result.append("\n");
4194
Dan Stozae77c7662016-05-13 11:37:28 -07004195 dumpBufferingStats(result);
4196
Andy McFadden4803b742012-09-24 19:07:20 -07004197 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004198 * Dump the visible layer list
4199 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004200 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004201 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004202 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4203 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004204 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004205
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004206 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004207 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7794ec12018-03-14 13:28:39 -07004208 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004209 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004210
4211 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004212 * Dump Display state
4213 */
4214
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004215 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004216 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004217 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004218 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4219 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004220 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004221 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004222 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004223
4224 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004225 * Dump SurfaceFlinger global state
4226 */
4227
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004228 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004229 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004230 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004231
Mathias Agopian888c8222012-08-04 21:10:38 -07004232 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004233 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004234
David Sodmanbc815282017-11-05 18:57:52 -08004235 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004236
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004237 if (hw) {
4238 hw->undefinedRegion.dump(result, "undefinedRegion");
4239 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4240 hw->getOrientation(), hw->isDisplayOn());
4241 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004242 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004243 " last eglSwapBuffers() time: %f us\n"
4244 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004245 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004246 " refresh-rate : %f fps\n"
4247 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004248 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004249 " gpu_to_cpu_unsupported : %d\n"
4250 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004251 mLastSwapBufferTime/1000.0,
4252 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004253 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004254 1e9 / activeConfig->getVsyncPeriod(),
4255 activeConfig->getDpiX(),
4256 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004257 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004258
Mathias Agopian74d211a2013-04-22 16:55:35 +02004259 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004260 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004261
Mathias Agopian74d211a2013-04-22 16:55:35 +02004262 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004263 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004264
4265 /*
4266 * VSYNC state
4267 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004268 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004269 result.append("\n");
4270
4271 /*
4272 * HWC layer minidump
4273 */
4274 for (size_t d = 0; d < mDisplays.size(); d++) {
4275 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4276 int32_t hwcId = displayDevice->getHwcDisplayId();
4277 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4278 continue;
4279 }
4280
4281 result.appendFormat("Display %d HWC layers:\n", hwcId);
4282 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004283 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004284 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004285 });
Dan Stozae22aec72016-08-01 13:20:59 -07004286 result.append("\n");
4287 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004288
4289 /*
4290 * Dump HWComposer state
4291 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004292 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004293 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004294 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004295 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004296 result.appendFormat(" h/w composer %s\n",
4297 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004298 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004299
4300 /*
4301 * Dump gralloc state
4302 */
4303 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4304 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004305
4306 /*
4307 * Dump VrFlinger state if in use.
4308 */
4309 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4310 result.append("VrFlinger state:\n");
4311 result.append(mVrFlinger->Dump().c_str());
4312 result.append("\n");
4313 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004314}
4315
Mathias Agopian13127d82013-03-05 17:47:11 -08004316const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004317SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004318 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004319 wp<IBinder> dpy;
4320 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4321 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4322 dpy = mDisplays.keyAt(i);
4323 break;
4324 }
4325 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004326 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004327 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4328 // Just use the primary display so we have something to return
4329 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4330 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004331 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004332}
4333
Keun young Park63f165f2012-08-31 10:53:36 -07004334bool SurfaceFlinger::startDdmConnection()
4335{
4336 void* libddmconnection_dso =
4337 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4338 if (!libddmconnection_dso) {
4339 return false;
4340 }
4341 void (*DdmConnection_start)(const char* name);
4342 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004343 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004344 if (!DdmConnection_start) {
4345 dlclose(libddmconnection_dso);
4346 return false;
4347 }
4348 (*DdmConnection_start)(getServiceName());
4349 return true;
4350}
4351
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004352status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004353 switch (code) {
4354 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004355 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004356 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004357 case CLEAR_ANIMATION_FRAME_STATS:
4358 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004359 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004360 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004361 case ENABLE_VSYNC_INJECTIONS:
4362 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004363 {
4364 // codes that require permission check
4365 IPCThreadState* ipc = IPCThreadState::self();
4366 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004367 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004368 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004369 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004370 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004371 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004372 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004373 break;
4374 }
Robert Carr1db73f62016-12-21 12:58:51 -08004375 /*
4376 * Calling setTransactionState is safe, because you need to have been
4377 * granted a reference to Client* and Handle* to do anything with it.
4378 *
4379 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4380 */
4381 case SET_TRANSACTION_STATE:
4382 case CREATE_SCOPED_CONNECTION:
4383 {
4384 return OK;
4385 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004386 case CAPTURE_SCREEN:
4387 {
4388 // codes that require permission check
4389 IPCThreadState* ipc = IPCThreadState::self();
4390 const int pid = ipc->getCallingPid();
4391 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004392 if ((uid != AID_GRAPHICS) &&
4393 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004394 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004395 return PERMISSION_DENIED;
4396 }
4397 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004398 }
chaviwa76b2712017-09-20 12:02:26 -07004399 case CAPTURE_LAYERS: {
4400 IPCThreadState* ipc = IPCThreadState::self();
4401 const int pid = ipc->getCallingPid();
4402 const int uid = ipc->getCallingUid();
4403 if ((uid != AID_GRAPHICS) &&
4404 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4405 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4406 return PERMISSION_DENIED;
4407 }
4408 break;
4409 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004410 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004411 return OK;
4412}
4413
4414status_t SurfaceFlinger::onTransact(
4415 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4416{
4417 status_t credentialCheck = CheckTransactCodeCredentials(code);
4418 if (credentialCheck != OK) {
4419 return credentialCheck;
4420 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004421
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004422 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4423 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004424 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004425 IPCThreadState* ipc = IPCThreadState::self();
4426 const int uid = ipc->getCallingUid();
4427 if (CC_UNLIKELY(uid != AID_SYSTEM
4428 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004429 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004430 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004431 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004432 return PERMISSION_DENIED;
4433 }
4434 int n;
4435 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004436 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004437 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004438 return NO_ERROR;
4439 case 1002: // SHOW_UPDATES
4440 n = data.readInt32();
4441 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004442 invalidateHwcGeometry();
4443 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004444 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004445 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004446 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004447 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004448 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004449 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004450 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004451 setTransactionFlags(
4452 eTransactionNeeded|
4453 eDisplayTransactionNeeded|
4454 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004455 return NO_ERROR;
4456 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004457 case 1006:{ // send empty update
4458 signalRefresh();
4459 return NO_ERROR;
4460 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004461 case 1008: // toggle use of hw composer
4462 n = data.readInt32();
4463 mDebugDisableHWC = n ? 1 : 0;
4464 invalidateHwcGeometry();
4465 repaintEverything();
4466 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004467 case 1009: // toggle use of transform hint
4468 n = data.readInt32();
4469 mDebugDisableTransformHint = n ? 1 : 0;
4470 invalidateHwcGeometry();
4471 repaintEverything();
4472 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004473 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004474 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004475 reply->writeInt32(0);
4476 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004477 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004478 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004479 return NO_ERROR;
4480 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004481 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004482 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004483 return NO_ERROR;
4484 }
4485 case 1014: {
4486 // daltonize
4487 n = data.readInt32();
4488 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004489 case 1:
4490 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4491 break;
4492 case 2:
4493 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4494 break;
4495 case 3:
4496 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4497 break;
4498 default:
4499 mDaltonizer.setType(ColorBlindnessType::None);
4500 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004501 }
4502 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004503 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004504 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004505 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004506 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004507 invalidateHwcGeometry();
4508 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004509 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004510 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004511 case 1015: {
4512 // apply a color matrix
4513 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004514 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004515 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004516 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004517 for (size_t j = 0; j < 4; j++) {
4518 mColorMatrix[i][j] = data.readFloat();
4519 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004520 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004521 } else {
4522 mColorMatrix = mat4();
4523 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004524
4525 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4526 // the division by w in the fragment shader
4527 float4 lastRow(transpose(mColorMatrix)[3]);
4528 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4529 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4530 }
4531
Alan Viverette9c5a3332013-09-12 20:04:35 -07004532 invalidateHwcGeometry();
4533 repaintEverything();
4534 return NO_ERROR;
4535 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004536 // This is an experimental interface
4537 // Needs to be shifted to proper binder interface when we productize
4538 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004539 n = data.readInt32();
4540 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004541 return NO_ERROR;
4542 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004543 case 1017: {
4544 n = data.readInt32();
4545 mForceFullDamage = static_cast<bool>(n);
4546 return NO_ERROR;
4547 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004548 case 1018: { // Modify Choreographer's phase offset
4549 n = data.readInt32();
4550 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4551 return NO_ERROR;
4552 }
4553 case 1019: { // Modify SurfaceFlinger's phase offset
4554 n = data.readInt32();
4555 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4556 return NO_ERROR;
4557 }
Irvel468051e2016-06-13 16:44:44 -07004558 case 1020: { // Layer updates interceptor
4559 n = data.readInt32();
4560 if (n) {
4561 ALOGV("Interceptor enabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004562 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004563 }
4564 else{
4565 ALOGV("Interceptor disabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004566 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004567 }
4568 return NO_ERROR;
4569 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004570 case 1021: { // Disable HWC virtual displays
4571 n = data.readInt32();
4572 mUseHwcVirtualDisplays = !n;
4573 return NO_ERROR;
4574 }
Romain Guy0147a172017-06-01 13:53:56 -07004575 case 1022: { // Set saturation boost
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004576 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004577
4578 invalidateHwcGeometry();
4579 repaintEverything();
4580 return NO_ERROR;
4581 }
Romain Guy54f154a2017-10-24 21:40:32 +01004582 case 1023: { // Set native mode
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004583 int32_t value = data.readInt32();
4584 if (value > 2) {
4585 return BAD_VALUE;
4586 }
4587 if (value == 2 && !mBuiltinDisplaySupportsEnhance) {
4588 return BAD_VALUE;
4589 }
Romain Guy54f154a2017-10-24 21:40:32 +01004590
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004591 mDisplayColorSetting = toDisplayColorSetting(value);
Romain Guy54f154a2017-10-24 21:40:32 +01004592 invalidateHwcGeometry();
4593 repaintEverything();
4594 return NO_ERROR;
4595 }
4596 case 1024: { // Is wide color gamut rendering/color management supported?
4597 reply->writeBool(hasWideColorDisplay);
4598 return NO_ERROR;
4599 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004600 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004601 n = data.readInt32();
4602 if (n) {
4603 ALOGV("LayerTracing enabled");
4604 mTracing.enable();
4605 doTracing("tracing.enable");
4606 reply->writeInt32(NO_ERROR);
4607 } else {
4608 ALOGV("LayerTracing disabled");
4609 status_t err = mTracing.disable();
4610 reply->writeInt32(err);
4611 }
4612 return NO_ERROR;
4613 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004614 case 1026: { // Get layer tracing status
4615 reply->writeBool(mTracing.isEnabled());
4616 return NO_ERROR;
4617 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004618 // Is a DisplayColorSetting supported?
4619 case 1027: {
4620 int32_t value = data.readInt32();
4621 switch (value) {
4622 case 0:
4623 reply->writeBool(hasWideColorDisplay);
4624 return NO_ERROR;
4625 case 1:
4626 reply->writeBool(true);
4627 return NO_ERROR;
4628 case 2:
4629 reply->writeBool(mBuiltinDisplaySupportsEnhance);
4630 return NO_ERROR;
4631 default:
4632 return BAD_VALUE;
4633 }
4634 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004635 }
4636 }
4637 return err;
4638}
4639
Steven Thomas6d8110b2017-08-31 18:24:21 -07004640void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004641 android_atomic_or(1, &mRepaintEverything);
4642 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004643}
4644
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004645// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4646class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004647public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004648 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4649 ~WindowDisconnector() {
4650 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004651 }
4652
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004653private:
4654 ANativeWindow* mWindow;
4655 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004656};
4657
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004658status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4659 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4660 int32_t minLayerZ, int32_t maxLayerZ,
4661 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004662 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004663 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004664
chaviwa76b2712017-09-20 12:02:26 -07004665 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4666
4667 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004668 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4669
chaviwa76b2712017-09-20 12:02:26 -07004670 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4671
4672 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4673 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004674 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004675}
4676
4677status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004678 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004679 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004680 ATRACE_CALL();
4681
4682 class LayerRenderArea : public RenderArea {
4683 public:
Robert Carr578038f2018-03-09 12:25:24 -08004684 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4685 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004686 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004687 mLayer(layer),
4688 mCrop(crop),
4689 mFlinger(flinger),
4690 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004691 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004692 Rect getBounds() const override {
4693 const Layer::State& layerState(mLayer->getDrawingState());
4694 return Rect(layerState.active.w, layerState.active.h);
4695 }
4696 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4697 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4698 bool isSecure() const override { return false; }
4699 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004700 Rect getSourceCrop() const override {
4701 if (mCrop.isEmpty()) {
4702 return getBounds();
4703 } else {
4704 return mCrop;
4705 }
4706 }
4707 bool getWideColorSupport() const override { return false; }
4708 Dataspace getDataSpace() const override { return Dataspace::UNKNOWN; }
Robert Carr578038f2018-03-09 12:25:24 -08004709
4710 class ReparentForDrawing {
4711 public:
4712 const sp<Layer>& oldParent;
4713 const sp<Layer>& newParent;
4714
4715 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4716 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004717 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004718 }
Robert Carr15eae092018-03-23 13:43:53 -07004719 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004720 };
4721
4722 void render(std::function<void()> drawLayers) override {
4723 if (!mChildrenOnly) {
4724 mTransform = mLayer->getTransform().inverse();
4725 drawLayers();
4726 } else {
4727 Rect bounds = getBounds();
4728 screenshotParentLayer =
4729 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4730 bounds.getWidth(), bounds.getHeight(), 0);
4731
4732 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4733 drawLayers();
4734 }
4735 }
chaviwa76b2712017-09-20 12:02:26 -07004736
chaviwa76b2712017-09-20 12:02:26 -07004737 private:
chaviw7206d492017-11-10 16:16:12 -08004738 const sp<Layer> mLayer;
4739 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004740
4741 // In the "childrenOnly" case we reparent the children to a screenshot
4742 // layer which has no properties set and which does not draw.
4743 sp<ContainerLayer> screenshotParentLayer;
4744 Transform mTransform;
4745
4746 SurfaceFlinger* mFlinger;
4747 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004748 };
4749
4750 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4751 auto parent = layerHandle->owner.promote();
4752
chaviw7206d492017-11-10 16:16:12 -08004753 if (parent == nullptr || parent->isPendingRemoval()) {
4754 ALOGE("captureLayers called with a removed parent");
4755 return NAME_NOT_FOUND;
4756 }
4757
Robert Carr578038f2018-03-09 12:25:24 -08004758 const int uid = IPCThreadState::self()->getCallingUid();
4759 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4760 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4761 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4762 return PERMISSION_DENIED;
4763 }
4764
chaviw7206d492017-11-10 16:16:12 -08004765 Rect crop(sourceCrop);
4766 if (sourceCrop.width() <= 0) {
4767 crop.left = 0;
4768 crop.right = parent->getCurrentState().active.w;
4769 }
4770
4771 if (sourceCrop.height() <= 0) {
4772 crop.top = 0;
4773 crop.bottom = parent->getCurrentState().active.h;
4774 }
4775
4776 int32_t reqWidth = crop.width() * frameScale;
4777 int32_t reqHeight = crop.height() * frameScale;
4778
Robert Carr578038f2018-03-09 12:25:24 -08004779 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004780
Robert Carr578038f2018-03-09 12:25:24 -08004781 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004782 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4783 if (!layer->isVisible()) {
4784 return;
Robert Carr578038f2018-03-09 12:25:24 -08004785 } else if (childrenOnly && layer == parent.get()) {
4786 return;
chaviwa76b2712017-09-20 12:02:26 -07004787 }
4788 visitor(layer);
4789 });
4790 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004791 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004792}
4793
4794status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4795 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004796 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004797 bool useIdentityTransform) {
4798 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004799
chaviwa76b2712017-09-20 12:02:26 -07004800 renderArea.updateDimensions();
4801
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004802 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4803 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4804 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4805 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004806
4807 // This mutex protects syncFd and captureResult for communication of the return values from the
4808 // main thread back to this Binder thread
4809 std::mutex captureMutex;
4810 std::condition_variable captureCondition;
4811 std::unique_lock<std::mutex> captureLock(captureMutex);
4812 int syncFd = -1;
4813 std::optional<status_t> captureResult;
4814
Robert Carr03480e22018-01-04 16:02:06 -08004815 const int uid = IPCThreadState::self()->getCallingUid();
4816 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4817
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004818 sp<LambdaMessage> message = new LambdaMessage([&]() {
4819 // If there is a refresh pending, bug out early and tell the binder thread to try again
4820 // after the refresh.
4821 if (mRefreshPending) {
4822 ATRACE_NAME("Skipping screenshot for now");
4823 std::unique_lock<std::mutex> captureLock(captureMutex);
4824 captureResult = std::make_optional<status_t>(EAGAIN);
4825 captureCondition.notify_one();
4826 return;
4827 }
4828
4829 status_t result = NO_ERROR;
4830 int fd = -1;
4831 {
4832 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004833 renderArea.render([&]() {
4834 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4835 useIdentityTransform, forSystem, &fd);
4836 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004837 }
4838
4839 {
4840 std::unique_lock<std::mutex> captureLock(captureMutex);
4841 syncFd = fd;
4842 captureResult = std::make_optional<status_t>(result);
4843 captureCondition.notify_one();
4844 }
4845 });
4846
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004847 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004848 if (result == NO_ERROR) {
4849 captureCondition.wait(captureLock, [&]() { return captureResult; });
4850 while (*captureResult == EAGAIN) {
4851 captureResult.reset();
4852 result = postMessageAsync(message);
4853 if (result != NO_ERROR) {
4854 return result;
4855 }
4856 captureCondition.wait(captureLock, [&]() { return captureResult; });
4857 }
4858 result = *captureResult;
4859 }
4860
4861 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004862 sync_wait(syncFd, -1);
4863 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004864 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004865
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004866 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004867}
4868
chaviwa76b2712017-09-20 12:02:26 -07004869void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4870 TraverseLayersFunction traverseLayers, bool yswap,
4871 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004872 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004873
Lloyd Pique144e1162017-12-20 16:44:52 -08004874 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004875
4876 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004877 const auto raWidth = renderArea.getWidth();
4878 const auto raHeight = renderArea.getHeight();
4879
4880 const auto reqWidth = renderArea.getReqWidth();
4881 const auto reqHeight = renderArea.getReqHeight();
4882 Rect sourceCrop = renderArea.getSourceCrop();
4883
4884 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4885 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004886
Dan Stozac1879002014-05-22 15:59:05 -07004887 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004888 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004889 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004890 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004891 }
4892
4893 // ensure that sourceCrop is inside screen
4894 if (sourceCrop.left < 0) {
4895 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4896 }
chaviwa76b2712017-09-20 12:02:26 -07004897 if (sourceCrop.right > raWidth) {
4898 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004899 }
4900 if (sourceCrop.top < 0) {
4901 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4902 }
chaviwa76b2712017-09-20 12:02:26 -07004903 if (sourceCrop.bottom > raHeight) {
4904 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004905 }
4906
Peiyong Lin34beb7a2018-03-28 11:57:12 -07004907 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004908 if (renderArea.getWideColorSupport()) {
4909 outputDataspace = renderArea.getDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004910 }
4911 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Romain Guy88d37dd2017-05-26 17:57:05 -07004912
Mathias Agopian180f10d2013-04-10 22:55:41 -07004913 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004914 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004915
4916 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004917 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4918 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004919 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004920
chaviw50da5042018-04-09 13:49:37 -07004921 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004922 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07004923 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004924
chaviwa76b2712017-09-20 12:02:26 -07004925 traverseLayers([&](Layer* layer) {
4926 if (filtering) layer->setFiltering(true);
4927 layer->draw(renderArea, useIdentityTransform);
4928 if (filtering) layer->setFiltering(false);
4929 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004930}
4931
chaviwa76b2712017-09-20 12:02:26 -07004932status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4933 TraverseLayersFunction traverseLayers,
4934 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004935 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08004936 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07004937 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004938 ATRACE_CALL();
4939
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004940 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004941
4942 traverseLayers([&](Layer* layer) {
4943 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4944 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004945
Robert Carr03480e22018-01-04 16:02:06 -08004946 // We allow the system server to take screenshots of secure layers for
4947 // use in situations like the Screen-rotation animation and place
4948 // the impetus on WindowManager to not persist them.
4949 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004950 ALOGW("FB is protected: PERMISSION_DENIED");
4951 return PERMISSION_DENIED;
4952 }
4953
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004954 // this binds the given EGLImage as a framebuffer for the
4955 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08004956 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08004957 if (bufferBond.getStatus() != NO_ERROR) {
4958 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004959 return INVALID_OPERATION;
4960 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004961
Dan Stozaabcda352017-06-01 14:37:39 -07004962 // this will in fact render into our dequeued buffer
4963 // via an FBO, which means we didn't have to create
4964 // an EGLSurface and therefore we're not
4965 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004966 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004967
Dan Stozaabcda352017-06-01 14:37:39 -07004968 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08004969 getRenderEngine().finish();
4970 *outSyncFd = -1;
4971
chaviwa76b2712017-09-20 12:02:26 -07004972 const auto reqWidth = renderArea.getReqWidth();
4973 const auto reqHeight = renderArea.getReqHeight();
4974
Dan Stozaabcda352017-06-01 14:37:39 -07004975 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4976 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004977 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004978 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08004979 } else {
4980 base::unique_fd syncFd = getRenderEngine().flush();
4981 if (syncFd < 0) {
4982 getRenderEngine().finish();
4983 }
4984 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07004985 }
4986
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004987 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004988}
4989
Mathias Agopiand5556842013-09-19 17:08:37 -07004990void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07004991 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004992 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004993 for (size_t y = 0; y < h; y++) {
4994 uint32_t const* p = (uint32_t const*)vaddr + y * s;
4995 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004996 if (p[x] != 0xFF000000) return;
4997 }
4998 }
chaviwa76b2712017-09-20 12:02:26 -07004999 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005000
Robert Carr2047fae2016-11-28 14:09:09 -08005001 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005002 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005003 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005004 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5005 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5006 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5007 static_cast<float>(state.color.a));
5008 i++;
5009 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005010 }
5011}
5012
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005013// ---------------------------------------------------------------------------
5014
Dan Stoza412903f2017-04-27 13:42:17 -07005015void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5016 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005017}
5018
Dan Stoza412903f2017-04-27 13:42:17 -07005019void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5020 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005021}
5022
chaviwa76b2712017-09-20 12:02:26 -07005023void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
5024 int32_t maxLayerZ,
5025 const LayerVector::Visitor& visitor) {
5026 // We loop through the first level of layers without traversing,
5027 // as we need to interpret min/max layer Z in the top level Z space.
5028 for (const auto& layer : mDrawingState.layersSortedByZ) {
5029 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5030 continue;
5031 }
5032 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005033 // relative layers are traversed in Layer::traverseInZOrder
5034 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005035 continue;
5036 }
5037 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005038 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5039 return;
5040 }
chaviwa76b2712017-09-20 12:02:26 -07005041 if (!layer->isVisible()) {
5042 return;
5043 }
5044 visitor(layer);
5045 });
5046 }
5047}
5048
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005049}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005050
5051
5052#if defined(__gl_h_)
5053#error "don't include gl/gl.h in this file"
5054#endif
5055
5056#if defined(__gl2_h_)
5057#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005058#endif