blob: 2d51bf4268e516bd568644b53ddf3a0f489f6374 [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),
Dan Stozab90cf072015-03-05 11:05:59 -0800247 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800248 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700249 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800250 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique09594832018-01-22 17:48:03 -0800251 mCreateBufferQueue(&BufferQueue::createBufferQueue),
252 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Pique2d3ee6d2018-01-17 13:42:24 -0800253
254SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800255 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800256
257 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
258 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
259
260 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
261 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
262
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800263 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
264 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800265
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700266 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
267 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
268
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700269 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
270 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
271
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800272 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
273 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
274
Steven Thomas050b2c82017-03-06 11:45:16 -0800275 // Vr flinger is only enabled on Daydream ready devices.
276 useVrFlinger = getBool< ISurfaceFlingerConfigs,
277 &ISurfaceFlingerConfigs::useVrFlinger>(false);
278
Fabien Sanglard1971b632017-03-10 14:50:03 -0800279 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
280 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
281
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600282 hasWideColorDisplay =
283 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
284
David Sodman99974d22017-11-28 12:04:33 -0800285 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700286
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800287 // debugging stuff...
288 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700289
Mathias Agopianb4b17302013-03-20 18:36:41 -0700290 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700291 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700292
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800293 property_get("debug.sf.showupdates", value, "0");
294 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700295
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700296 property_get("debug.sf.ddms", value, "0");
297 mDebugDDMS = atoi(value);
298 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700299 if (!startDdmConnection()) {
300 // start failed, and DDMS debugging not enabled
301 mDebugDDMS = 0;
302 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700303 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700304 ALOGI_IF(mDebugRegion, "showupdates enabled");
305 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700306
307 property_get("debug.sf.disable_backpressure", value, "0");
308 mPropagateBackpressure = !atoi(value);
309 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700310
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800311 property_get("debug.sf.enable_hwc_vds", value, "0");
312 mUseHwcVirtualDisplays = atoi(value);
313 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800314
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800315 property_get("ro.sf.disable_triple_buffer", value, "1");
316 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800317 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700318
Dan Stoza0a0158c2018-03-16 13:38:54 -0700319 // TODO (b/74616334): Reduce the default value once we isolate the leak
320 const size_t defaultListSize = 4 * MAX_LAYERS;
321 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
322 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
323
Dan Stoza2713c302018-03-28 17:07:36 -0700324 property_get("debug.sf.early_phase_offset_ns", value, "0");
325 const int earlyWakeupOffsetOffsetNs = atoi(value);
326 ALOGI_IF(earlyWakeupOffsetOffsetNs != 0, "Enabling separate early offset");
327 mVsyncModulator.setPhaseOffsets(sfVsyncPhaseOffsetNs - earlyWakeupOffsetOffsetNs,
328 sfVsyncPhaseOffsetNs);
329
Romain Guy11d63f42017-07-20 12:47:14 -0700330 // We should be reading 'persist.sys.sf.color_saturation' here
331 // but since /data may be encrypted, we need to wait until after vold
332 // comes online to attempt to read the property. The property is
333 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800334
335 if (useTrebleTestingOverride()) {
336 // Without the override SurfaceFlinger cannot connect to HIDL
337 // services that are not listed in the manifests. Considered
338 // deriving the setting from the set service name, but it
339 // would be brittle if the name that's not 'default' is used
340 // for production purposes later on.
341 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
342 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800343}
344
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800345void SurfaceFlinger::onFirstRef()
346{
Lloyd Pique9123ae52018-01-22 17:14:00 -0800347 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800348}
349
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800350SurfaceFlinger::~SurfaceFlinger()
351{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800352}
353
Dan Stozac7014012014-02-14 15:03:43 -0800354void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800355{
356 // the window manager died on us. prepare its eulogy.
357
Andy McFadden13a082e2012-08-24 10:16:42 -0700358 // restore initial conditions (default device unblank, etc)
359 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800360
361 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700362 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800363}
364
Robert Carr1db73f62016-12-21 12:58:51 -0800365static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700366 status_t err = client->initCheck();
367 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800368 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800369 }
Robert Carr1db73f62016-12-21 12:58:51 -0800370 return nullptr;
371}
372
373sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
374 return initClient(new Client(this));
375}
376
377sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
378 const sp<IGraphicBufferProducer>& gbp) {
379 if (authenticateSurfaceTexture(gbp) == false) {
380 return nullptr;
381 }
382 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
383 if (layer == nullptr) {
384 return nullptr;
385 }
386
387 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800388}
389
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700390sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
391 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700392{
393 class DisplayToken : public BBinder {
394 sp<SurfaceFlinger> flinger;
395 virtual ~DisplayToken() {
396 // no more references, this display must be terminated
397 Mutex::Autolock _l(flinger->mStateLock);
398 flinger->mCurrentState.displays.removeItem(this);
399 flinger->setTransactionFlags(eDisplayTransactionNeeded);
400 }
401 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700402 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700403 : flinger(flinger) {
404 }
405 };
406
407 sp<BBinder> token = new DisplayToken(this);
408
409 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700410 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700411 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700412 mCurrentState.displays.add(token, info);
Lloyd Pique4d234852018-01-22 17:21:36 -0800413 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700414 return token;
415}
416
Jesse Hall6c913be2013-08-08 12:15:49 -0700417void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
418 Mutex::Autolock _l(mStateLock);
419
420 ssize_t idx = mCurrentState.displays.indexOfKey(display);
421 if (idx < 0) {
422 ALOGW("destroyDisplay: invalid display token");
423 return;
424 }
425
426 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
427 if (!info.isVirtualDisplay()) {
428 ALOGE("destroyDisplay called for non-virtual display");
429 return;
430 }
Lloyd Pique4d234852018-01-22 17:21:36 -0800431 mInterceptor->saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700432 mCurrentState.displays.removeItemsAt(idx);
433 setTransactionFlags(eDisplayTransactionNeeded);
434}
435
Mathias Agopiane57f2922012-08-09 16:29:12 -0700436sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700437 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700438 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800439 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700440 }
Jesse Hall692c7232012-11-08 15:41:56 -0800441 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700442}
443
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800444void SurfaceFlinger::bootFinished()
445{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700446 if (mStartPropertySetThread->join() != NO_ERROR) {
447 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800448 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800449 const nsecs_t now = systemTime();
450 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000451 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700452
453 // wait patiently for the window manager death
454 const String16 name("window");
455 sp<IBinder> window(defaultServiceManager()->getService(name));
456 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700457 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700458 }
459
Steven Thomas050b2c82017-03-06 11:45:16 -0800460 if (mVrFlinger) {
461 mVrFlinger->OnBootFinished();
462 }
463
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700464 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700465 // formerly we would just kill the process, but we now ask it to exit so it
466 // can choose where to stop the animation.
467 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700468
469 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
470 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
471 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700472
Thierry Strudel2924d012017-08-14 15:19:37 -0700473 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700474 readPersistentProperties();
475 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700476 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800477}
478
Dan Stoza9fdb7e02018-06-21 12:10:12 -0700479uint32_t SurfaceFlinger::getNewTexture() {
480 {
481 std::lock_guard lock(mTexturePoolMutex);
482 if (!mTexturePool.empty()) {
483 uint32_t name = mTexturePool.back();
484 mTexturePool.pop_back();
485 ATRACE_INT("TexturePoolSize", mTexturePool.size());
486 return name;
487 }
488
489 // The pool was too small, so increase it for the future
490 ++mTexturePoolSize;
491 }
492
493 // The pool was empty, so we need to get a new texture name directly using a
494 // blocking call to the main thread
495 uint32_t name = 0;
496 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
497 return name;
498}
499
Mathias Agopian3f844832013-08-07 21:24:32 -0700500void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700501 class MessageDestroyGLTexture : public MessageBase {
Lloyd Pique144e1162017-12-20 16:44:52 -0800502 RE::RenderEngine& engine;
Mathias Agopian3f844832013-08-07 21:24:32 -0700503 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700504 public:
Lloyd Pique144e1162017-12-20 16:44:52 -0800505 MessageDestroyGLTexture(RE::RenderEngine& engine, uint32_t texture)
506 : engine(engine), texture(texture) {}
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700507 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700508 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700509 return true;
510 }
511 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700512 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700513}
514
Lloyd Piquee83f9312018-02-01 12:53:17 -0800515class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700516public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700517 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000518 const char* name) :
519 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700520 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700521 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000522 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
523 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700524 mDispSync(dispSync),
525 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700526 mVsyncMutex(),
527 mPhaseOffset(phaseOffset),
528 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700529
Lloyd Piquee83f9312018-02-01 12:53:17 -0800530 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700531
Lloyd Piquee83f9312018-02-01 12:53:17 -0800532 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700533 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700534 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000535 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700536 static_cast<DispSync::Callback*>(this));
537 if (err != NO_ERROR) {
538 ALOGE("error registering vsync callback: %s (%d)",
539 strerror(-err), err);
540 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700541 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700542 } else {
543 status_t err = mDispSync->removeEventListener(
544 static_cast<DispSync::Callback*>(this));
545 if (err != NO_ERROR) {
546 ALOGE("error unregistering vsync callback: %s (%d)",
547 strerror(-err), err);
548 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700549 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700550 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700551 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700552 }
553
Lloyd Piquee83f9312018-02-01 12:53:17 -0800554 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700555 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700556 mCallback = callback;
557 }
558
Lloyd Piquee83f9312018-02-01 12:53:17 -0800559 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700560 Mutex::Autolock lock(mVsyncMutex);
561
562 // Normalize phaseOffset to [0, period)
563 auto period = mDispSync->getPeriod();
564 phaseOffset %= period;
565 if (phaseOffset < 0) {
566 // If we're here, then phaseOffset is in (-period, 0). After this
567 // operation, it will be in (0, period)
568 phaseOffset += period;
569 }
570 mPhaseOffset = phaseOffset;
571
572 // If we're not enabled, we don't need to mess with the listeners
573 if (!mEnabled) {
574 return;
575 }
576
Dan Stoza2713c302018-03-28 17:07:36 -0700577 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
578 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700579 if (err != NO_ERROR) {
Dan Stoza2713c302018-03-28 17:07:36 -0700580 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700581 strerror(-err), err);
582 }
583 }
584
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700585private:
586 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800587 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700588 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700589 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700590 callback = mCallback;
591
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700592 if (mTraceVsync) {
593 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700594 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700595 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700596 }
597
Peiyong Lin566a3b42018-01-09 18:22:43 -0800598 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700599 callback->onVSyncEvent(when);
600 }
601 }
602
Tim Murray4a4e4a22016-04-19 16:29:23 +0000603 const char* const mName;
604
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700605 int mValue;
606
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700607 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700608 const String8 mVsyncOnLabel;
609 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700610
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700611 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700612
613 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800614 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700615
616 Mutex mVsyncMutex; // Protects the following
617 nsecs_t mPhaseOffset;
618 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700619};
620
Lloyd Piquee83f9312018-02-01 12:53:17 -0800621class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700622public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800623 InjectVSyncSource() = default;
624 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700625
Lloyd Piquee83f9312018-02-01 12:53:17 -0800626 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700627 std::lock_guard<std::mutex> lock(mCallbackMutex);
628 mCallback = callback;
629 }
630
Lloyd Piquee83f9312018-02-01 12:53:17 -0800631 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700632 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700633 if (mCallback) {
634 mCallback->onVSyncEvent(when);
635 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700636 }
637
Lloyd Piquee83f9312018-02-01 12:53:17 -0800638 void setVSyncEnabled(bool) override {}
639 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700640
641private:
642 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800643 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700644};
645
Wei Wangf9b05ee2017-07-19 20:59:39 -0700646// Do not call property_set on main thread which will be blocked by init
647// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700648void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700649 ALOGI( "SurfaceFlinger's main thread ready to run. "
650 "Initializing graphics H/W...");
651
Thierry Strudel2924d012017-08-14 15:19:37 -0700652 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900653
Steven Thomasb02664d2017-07-26 18:48:28 -0700654 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800655
Steven Thomasb02664d2017-07-26 18:48:28 -0700656 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800657 mEventThreadSource =
658 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
659 true, "app");
660 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(), *this, false,
661 "appEventThread");
662 mSfEventThreadSource =
663 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
664 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800665
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800666 mSFEventThread = std::make_unique<impl::EventThread>(mSfEventThreadSource.get(), *this, true,
667 "sfEventThread");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800668 mEventQueue->setEventThread(mSFEventThread.get());
Dan Stoza2713c302018-03-28 17:07:36 -0700669 mVsyncModulator.setEventThread(mSFEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800670
Steven Thomasb02664d2017-07-26 18:48:28 -0700671 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800672 getBE().mRenderEngine =
673 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
674 hasWideColorDisplay
675 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
676 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800677 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700678
679 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
680 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800681 getBE().mHwc.reset(
682 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700683 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800684 // Process any initial hotplug and resulting display changes.
685 processDisplayHotplugEventsLocked();
686 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
687 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800688
Lloyd Piquefcd86612017-12-14 17:15:36 -0800689 // make the default display GLContext current so that we can create textures
690 // when creating Layers (which may happens before we render something)
691 getDefaultDisplayDeviceLocked()->makeCurrent();
692
Steven Thomas050b2c82017-03-06 11:45:16 -0800693 if (useVrFlinger) {
694 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700695 // This callback is called from the vr flinger dispatch thread. We
696 // need to call signalTransaction(), which requires holding
697 // mStateLock when we're not on the main thread. Acquiring
698 // mStateLock from the vr flinger dispatch thread might trigger a
699 // deadlock in surface flinger (see b/66916578), so post a message
700 // to be handled on the main thread instead.
701 sp<LambdaMessage> message = new LambdaMessage([=]() {
702 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
703 mVrFlingerRequestsDisplay = requestDisplay;
704 signalTransaction();
705 });
706 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800707 };
David Sodman105b7dc2017-11-04 20:28:14 -0700708 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
709 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800710 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800711 if (!mVrFlinger) {
712 ALOGE("Failed to start vrflinger");
713 }
714 }
715
Lloyd Pique0c3a8832018-01-22 17:31:47 -0800716 mEventControlThread = std::make_unique<impl::EventControlThread>(
717 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700718
Mathias Agopian92a979a2012-08-02 18:32:23 -0700719 // initialize our drawing state
720 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700721
Andy McFadden13a082e2012-08-24 10:16:42 -0700722 // set initial conditions (e.g. unblank default device)
723 initializeDisplays();
724
David Sodmanbc815282017-11-05 18:57:52 -0800725 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700726
Wei Wangf9b05ee2017-07-19 20:59:39 -0700727 // Inform native graphics APIs whether the present timestamp is supported:
728 if (getHwComposer().hasCapability(
729 HWC2::Capability::PresentFenceIsNotReliable)) {
730 mStartPropertySetThread = new StartPropertySetThread(false);
731 } else {
732 mStartPropertySetThread = new StartPropertySetThread(true);
733 }
734
735 if (mStartPropertySetThread->Start() != NO_ERROR) {
736 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800737 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800738
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800739 mLegacySrgbSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(HWC_DISPLAY_PRIMARY,
740 Dataspace::SRGB_LINEAR);
741
Dan Stoza9e56aa02015-11-02 13:00:03 -0800742 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700743}
744
Romain Guy11d63f42017-07-20 12:47:14 -0700745void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700746 Mutex::Autolock _l(mStateLock);
747
Romain Guy11d63f42017-07-20 12:47:14 -0700748 char value[PROPERTY_VALUE_MAX];
749
750 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800751 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700752 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800753 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100754
755 property_get("persist.sys.sf.native_mode", value, "0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800756 mDisplayColorSetting = toDisplayColorSetting(atoi(value));
757 ALOGV("Display Color Setting is set to %s.",
758 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Romain Guy11d63f42017-07-20 12:47:14 -0700759}
760
Mathias Agopiana67e4182012-06-19 17:26:12 -0700761void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800762 // Start boot animation service by setting a property mailbox
763 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700764 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800765 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700766 if (mStartPropertySetThread->join() != NO_ERROR) {
767 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800768 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700769}
770
Mathias Agopian875d8e12013-06-07 15:35:48 -0700771size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800772 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700773}
774
Mathias Agopian875d8e12013-06-07 15:35:48 -0700775size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800776 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700777}
778
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800779// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800780
Jamie Gennis582270d2011-08-17 18:19:00 -0700781bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800782 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800783 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800784 return authenticateSurfaceTextureLocked(bufferProducer);
785}
786
787bool SurfaceFlinger::authenticateSurfaceTextureLocked(
788 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800789 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800790 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800791}
792
Brian Anderson6b376712017-04-04 10:51:39 -0700793status_t SurfaceFlinger::getSupportedFrameTimestamps(
794 std::vector<FrameEvent>* outSupported) const {
795 *outSupported = {
796 FrameEvent::REQUESTED_PRESENT,
797 FrameEvent::ACQUIRE,
798 FrameEvent::LATCH,
799 FrameEvent::FIRST_REFRESH_START,
800 FrameEvent::LAST_REFRESH_START,
801 FrameEvent::GPU_COMPOSITION_DONE,
802 FrameEvent::DEQUEUE_READY,
803 FrameEvent::RELEASE,
804 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700805 ConditionalLock _l(mStateLock,
806 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700807 if (!getHwComposer().hasCapability(
808 HWC2::Capability::PresentFenceIsNotReliable)) {
809 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
810 }
811 return NO_ERROR;
812}
813
Dan Stoza7f7da322014-05-02 15:26:25 -0700814status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
815 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800816 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700817 return BAD_VALUE;
818 }
819
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500820 if (!display.get())
821 return NAME_NOT_FOUND;
822
Jesse Hall692c7232012-11-08 15:41:56 -0800823 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700824 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800825 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700826 type = i;
827 break;
828 }
829 }
830
831 if (type < 0) {
832 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700833 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700834
Mathias Agopian8b736f12012-08-13 17:54:26 -0700835 // TODO: Not sure if display density should handled by SF any longer
836 class Density {
837 static int getDensityFromProperty(char const* propName) {
838 char property[PROPERTY_VALUE_MAX];
839 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800840 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700841 density = atoi(property);
842 }
843 return density;
844 }
845 public:
846 static int getEmuDensity() {
847 return getDensityFromProperty("qemu.sf.lcd_density"); }
848 static int getBuildDensity() {
849 return getDensityFromProperty("ro.sf.lcd_density"); }
850 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700851
Dan Stoza7f7da322014-05-02 15:26:25 -0700852 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700853
Steven Thomas6d8110b2017-08-31 18:24:21 -0700854 ConditionalLock _l(mStateLock,
855 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800856 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700857 DisplayInfo info = DisplayInfo();
858
Dan Stoza9e56aa02015-11-02 13:00:03 -0800859 float xdpi = hwConfig->getDpiX();
860 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700861
862 if (type == DisplayDevice::DISPLAY_PRIMARY) {
863 // The density of the device is provided by a build property
864 float density = Density::getBuildDensity() / 160.0f;
865 if (density == 0) {
866 // the build doesn't provide a density -- this is wrong!
867 // use xdpi instead
868 ALOGE("ro.sf.lcd_density must be defined as a build property");
869 density = xdpi / 160.0f;
870 }
871 if (Density::getEmuDensity()) {
872 // if "qemu.sf.lcd_density" is specified, it overrides everything
873 xdpi = ydpi = density = Density::getEmuDensity();
874 density /= 160.0f;
875 }
876 info.density = density;
877
878 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700879 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800880 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700881 } else {
882 // TODO: where should this value come from?
883 static const int TV_DENSITY = 213;
884 info.density = TV_DENSITY / 160.0f;
885 info.orientation = 0;
886 }
887
Dan Stoza9e56aa02015-11-02 13:00:03 -0800888 info.w = hwConfig->getWidth();
889 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700890 info.xdpi = xdpi;
891 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800892 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900893 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800894
Andy McFadden91b2ca82014-06-13 14:04:23 -0700895 // This is how far in advance a buffer must be queued for
896 // presentation at a given time. If you want a buffer to appear
897 // on the screen at time N, you must submit the buffer before
898 // (N - presentationDeadline).
899 //
900 // Normally it's one full refresh period (to give SF a chance to
901 // latch the buffer), but this can be reduced by configuring a
902 // DispSync offset. Any additional delays introduced by the hardware
903 // composer or panel must be accounted for here.
904 //
905 // We add an additional 1ms to allow for processing time and
906 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800907 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800908 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700909
910 // All non-virtual displays are currently considered secure.
911 info.secure = true;
912
Michael Wright28f24d02016-07-12 13:30:53 -0700913 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700914 }
915
Dan Stoza7f7da322014-05-02 15:26:25 -0700916 return NO_ERROR;
917}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700918
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800919status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700920 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800921 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700922 return BAD_VALUE;
923 }
924
925 // FIXME for now we always return stats for the primary display
926 memset(stats, 0, sizeof(*stats));
927 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
928 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
929 return NO_ERROR;
930}
931
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700932int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800933 if (display == nullptr) {
934 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800935 return BAD_VALUE;
936 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700937
938 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800939 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700940 return device->getActiveConfig();
941 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700942
Dan Stoza24a42e92015-03-09 10:04:11 -0700943 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700944}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700945
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700946void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
947 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
948 this);
949 int32_t type = hw->getDisplayType();
950 int currentMode = hw->getActiveConfig();
951
952 if (mode == currentMode) {
953 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
954 return;
955 }
956
957 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
958 ALOGW("Trying to set config for virtual display");
959 return;
960 }
961
962 hw->setActiveConfig(mode);
963 getHwComposer().setActiveConfig(type, mode);
964}
965
966status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
967 class MessageSetActiveConfig: public MessageBase {
968 SurfaceFlinger& mFlinger;
969 sp<IBinder> mDisplay;
970 int mMode;
971 public:
972 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
973 int mode) :
974 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
975 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700976 Vector<DisplayInfo> configs;
977 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700978 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700979 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700980 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700981 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700982 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700983 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800984 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700985 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700986 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700987 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
988 ALOGW("Attempt to set active config = %d for virtual display",
989 mMode);
990 } else {
991 mFlinger.setActiveConfigInternal(hw, mMode);
992 }
993 return true;
994 }
995 };
996 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
997 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700998 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700999}
Michael Wright28f24d02016-07-12 13:30:53 -07001000status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001001 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001002 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
1003 return BAD_VALUE;
1004 }
1005
1006 if (!display.get()) {
1007 return NAME_NOT_FOUND;
1008 }
1009
1010 int32_t type = NAME_NOT_FOUND;
1011 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
1012 if (display == mBuiltinDisplays[i]) {
1013 type = i;
1014 break;
1015 }
1016 }
1017
1018 if (type < 0) {
1019 return type;
1020 }
1021
Peiyong Lina52f0292018-03-14 17:26:31 -07001022 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001023 {
1024 ConditionalLock _l(mStateLock,
1025 std::this_thread::get_id() != mMainThreadId);
1026 modes = getHwComposer().getColorModes(type);
1027 }
Michael Wright28f24d02016-07-12 13:30:53 -07001028 outColorModes->clear();
1029 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1030
1031 return NO_ERROR;
1032}
1033
Peiyong Lina52f0292018-03-14 17:26:31 -07001034ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001035 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -07001036 if (device != nullptr) {
1037 return device->getActiveColorMode();
1038 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001039 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001040}
1041
1042void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001043 ColorMode mode, Dataspace dataSpace,
1044 RenderIntent renderIntent) {
Michael Wright28f24d02016-07-12 13:30:53 -07001045 int32_t type = hw->getDisplayType();
Peiyong Lina52f0292018-03-14 17:26:31 -07001046 ColorMode currentMode = hw->getActiveColorMode();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001047 Dataspace currentDataSpace = hw->getCompositionDataSpace();
Peiyong Lin38e9a562018-04-10 16:24:20 -07001048 RenderIntent currentRenderIntent = hw->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001049
Peiyong Lin38e9a562018-04-10 16:24:20 -07001050 if (mode == currentMode && dataSpace == currentDataSpace &&
1051 renderIntent == currentRenderIntent) {
1052 return;
1053 }
1054
1055 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1056 ALOGW("Trying to set config for virtual display");
1057 return;
1058 }
1059
1060 hw->setActiveColorMode(mode);
1061 hw->setCompositionDataSpace(dataSpace);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001062 hw->setActiveRenderIntent(renderIntent);
1063 getHwComposer().setActiveColorMode(type, mode, renderIntent);
1064
1065 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
1066 decodeColorMode(mode).c_str(), mode,
1067 decodeRenderIntent(renderIntent).c_str(), renderIntent,
1068 hw->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001069}
1070
1071
1072status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001073 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -07001074 class MessageSetActiveColorMode: public MessageBase {
1075 SurfaceFlinger& mFlinger;
1076 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -07001077 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001078 public:
1079 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -07001080 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -07001081 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1082 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -07001083 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001084 mFlinger.getDisplayColorModes(mDisplay, &modes);
1085 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -07001086 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001087 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1088 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001089 return true;
1090 }
1091 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1092 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001093 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1094 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001095 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001096 ALOGW("Attempt to set active color mode %s %d for virtual display",
1097 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001098 } else {
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001099 mFlinger.setActiveColorModeInternal(hw, mMode, Dataspace::UNKNOWN,
1100 RenderIntent::COLORIMETRIC);
Michael Wright28f24d02016-07-12 13:30:53 -07001101 }
1102 return true;
1103 }
1104 };
1105 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1106 postMessageSync(msg);
1107 return NO_ERROR;
1108}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001109
Svetoslavd85084b2014-03-20 10:28:31 -07001110status_t SurfaceFlinger::clearAnimationFrameStats() {
1111 Mutex::Autolock _l(mStateLock);
1112 mAnimFrameTracker.clearStats();
1113 return NO_ERROR;
1114}
1115
1116status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1117 Mutex::Autolock _l(mStateLock);
1118 mAnimFrameTracker.getStats(outStats);
1119 return NO_ERROR;
1120}
1121
Dan Stozac4f471e2016-03-24 09:31:08 -07001122status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1123 HdrCapabilities* outCapabilities) const {
1124 Mutex::Autolock _l(mStateLock);
1125
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001126 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001127 if (displayDevice == nullptr) {
1128 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1129 return BAD_VALUE;
1130 }
1131
Peiyong Linfb069302018-04-25 14:34:31 -07001132 // At this point the DisplayDeivce should already be set up,
1133 // meaning the luminance information is already queried from
1134 // hardware composer and stored properly.
1135 const HdrCapabilities& capabilities = displayDevice->getHdrCapabilities();
1136 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1137 capabilities.getDesiredMaxLuminance(),
1138 capabilities.getDesiredMaxAverageLuminance(),
1139 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001140
1141 return NO_ERROR;
1142}
1143
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001144status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001145 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1146 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001147
Chia-I Wu90f669f2017-10-05 14:24:41 -07001148 if (mInjectVSyncs == enable) {
1149 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001150 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001151
1152 if (enable) {
1153 ALOGV("VSync Injections enabled");
1154 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001155 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique0fcde1b2017-12-20 16:50:21 -08001156 mInjectorEventThread =
1157 std::make_unique<impl::EventThread>(mVSyncInjector.get(), *this, false,
1158 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001159 }
Lloyd Pique9123ae52018-01-22 17:14:00 -08001160 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001161 } else {
1162 ALOGV("VSync Injections disabled");
Lloyd Pique9123ae52018-01-22 17:14:00 -08001163 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001164 }
1165
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001166 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001167 });
1168 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001169 return NO_ERROR;
1170}
1171
1172status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001173 Mutex::Autolock _l(mStateLock);
1174
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001175 if (!mInjectVSyncs) {
1176 ALOGE("VSync Injections not enabled");
1177 return BAD_VALUE;
1178 }
1179 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1180 ALOGV("Injecting VSync inside SurfaceFlinger");
1181 mVSyncInjector->onInjectSyncEvent(when);
1182 }
1183 return NO_ERROR;
1184}
1185
Lloyd Pique755e3192018-01-31 16:46:15 -08001186status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1187 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001188 IPCThreadState* ipc = IPCThreadState::self();
1189 const int pid = ipc->getCallingPid();
1190 const int uid = ipc->getCallingUid();
1191 if ((uid != AID_SHELL) &&
1192 !PermissionCache::checkPermission(sDump, pid, uid)) {
1193 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1194 return PERMISSION_DENIED;
1195 }
1196
1197 // Try to acquire a lock for 1s, fail gracefully
1198 const status_t err = mStateLock.timedLock(s2ns(1));
1199 const bool locked = (err == NO_ERROR);
1200 if (!locked) {
1201 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1202 return TIMED_OUT;
1203 }
1204
1205 outLayers->clear();
1206 mCurrentState.traverseInZOrder([&](Layer* layer) {
1207 outLayers->push_back(layer->getLayerDebugInfo());
1208 });
1209
1210 mStateLock.unlock();
1211 return NO_ERROR;
1212}
1213
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001214// ----------------------------------------------------------------------------
1215
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001216sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1217 ISurfaceComposer::VsyncSource vsyncSource) {
1218 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1219 return mSFEventThread->createEventConnection();
1220 } else {
1221 return mEventThread->createEventConnection();
1222 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001223}
1224
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001225// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001226
1227void SurfaceFlinger::waitForEvent() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001228 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001229}
1230
1231void SurfaceFlinger::signalTransaction() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001232 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001233}
1234
1235void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001236 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001237}
1238
1239void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001240 mRefreshPending = true;
Lloyd Pique9123ae52018-01-22 17:14:00 -08001241 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001242}
1243
1244status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001245 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001246 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001247}
1248
1249status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001250 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001251 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001252 if (res == NO_ERROR) {
1253 msg->wait();
1254 }
1255 return res;
1256}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001257
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001258void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001259 do {
1260 waitForEvent();
1261 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001262}
1263
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001264void SurfaceFlinger::enableHardwareVsync() {
1265 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001266 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001267 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001268 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1269 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001270 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001271 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001272}
1273
Jesse Hall948fe0c2013-10-14 12:56:09 -07001274void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001275 Mutex::Autolock _l(mHWVsyncLock);
1276
Jesse Hall948fe0c2013-10-14 12:56:09 -07001277 if (makeAvailable) {
1278 mHWVsyncAvailable = true;
1279 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001280 // Hardware vsync is not currently available, so abort the resync
1281 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001282 return;
1283 }
1284
David Sodman105b7dc2017-11-04 20:28:14 -07001285 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001286 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001287
1288 mPrimaryDispSync.reset();
1289 mPrimaryDispSync.setPeriod(period);
1290
1291 if (!mPrimaryHWVsyncEnabled) {
1292 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001293 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1294 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001295 mPrimaryHWVsyncEnabled = true;
1296 }
1297}
1298
Jesse Hall948fe0c2013-10-14 12:56:09 -07001299void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001300 Mutex::Autolock _l(mHWVsyncLock);
1301 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001302 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1303 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001304 mPrimaryDispSync.endResync();
1305 mPrimaryHWVsyncEnabled = false;
1306 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001307 if (makeUnavailable) {
1308 mHWVsyncAvailable = false;
1309 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001310}
1311
Tim Murray4a4e4a22016-04-19 16:29:23 +00001312void SurfaceFlinger::resyncWithRateLimit() {
1313 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001314
1315 // No explicit locking is needed here since EventThread holds a lock while calling this method
1316 static nsecs_t sLastResyncAttempted = 0;
1317 const nsecs_t now = systemTime();
1318 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001319 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001320 }
Dan Stoza57164302017-05-08 14:03:54 -07001321 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001322}
1323
Steven Thomasb02664d2017-07-26 18:48:28 -07001324void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1325 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001326 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001327 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001328 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001329 return;
1330 }
1331
1332 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001333 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001334 return;
1335 }
1336
Jamie Gennisd1700752013-10-14 12:22:52 -07001337 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001338
Jamie Gennisd1700752013-10-14 12:22:52 -07001339 { // Scope for the lock
1340 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001341 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001342 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001343 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001344 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001345
1346 if (needsHwVsync) {
1347 enableHardwareVsync();
1348 } else {
1349 disableHardwareVsync(false);
1350 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001351}
1352
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001353void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001354 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1355 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001356}
1357
Lloyd Pique715a2c12017-12-14 17:18:08 -08001358void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1359 HWC2::Connection connection) {
1360 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1361 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001362
Lloyd Piqueba04e622017-12-14 17:11:26 -08001363 // Ignore events that do not have the right sequenceId.
1364 if (sequenceId != getBE().mComposerSequenceId) {
1365 return;
1366 }
1367
Steven Thomasb02664d2017-07-26 18:48:28 -07001368 // Only lock if we're not on the main thread. This function is normally
1369 // called on a hwbinder thread, but for the primary display it's called on
1370 // the main thread with the state lock already held, so don't attempt to
1371 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001372 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001373
Lloyd Pique715a2c12017-12-14 17:18:08 -08001374 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001375
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001376 if (std::this_thread::get_id() == mMainThreadId) {
1377 // Process all pending hot plug events immediately if we are on the main thread.
1378 processDisplayHotplugEventsLocked();
1379 }
1380
Lloyd Piqueba04e622017-12-14 17:11:26 -08001381 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001382}
1383
Steven Thomasb02664d2017-07-26 18:48:28 -07001384void SurfaceFlinger::onRefreshReceived(int sequenceId,
1385 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001386 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001387 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001388 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001389 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001390 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001391}
1392
Dan Stoza9e56aa02015-11-02 13:00:03 -08001393void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001394 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001395 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001396 getHwComposer().setVsyncEnabled(disp,
1397 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001398}
1399
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001400// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001401void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001402 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001403 // Clear the drawing state so that the logic inside of
1404 // handleTransactionLocked will fire. It will determine the delta between
1405 // mCurrentState and mDrawingState and re-apply all changes when we make the
1406 // transition.
1407 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001408 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001409 mDisplays.clear();
1410}
1411
Steven Thomas050b2c82017-03-06 11:45:16 -08001412void SurfaceFlinger::updateVrFlinger() {
1413 if (!mVrFlinger)
1414 return;
1415 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001416 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001417 return;
1418 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001419
David Sodman105b7dc2017-11-04 20:28:14 -07001420 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001421 ALOGE("Vr flinger is only supported for remote hardware composer"
1422 " service connections. Ignoring request to transition to vr"
1423 " flinger.");
1424 mVrFlingerRequestsDisplay = false;
1425 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001426 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001427
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001428 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001429
Steven Thomasb02664d2017-07-26 18:48:28 -07001430 int currentDisplayPowerMode = getDisplayDeviceLocked(
1431 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001432
Steven Thomasb02664d2017-07-26 18:48:28 -07001433 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001434 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001435 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001436
Steven Thomasb02664d2017-07-26 18:48:28 -07001437 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001438 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001439 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1440 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001441 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001442
David Sodman105b7dc2017-11-04 20:28:14 -07001443 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1444 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001445
1446 if (vrFlingerRequestsDisplay) {
1447 mVrFlinger->GrantDisplayOwnership();
1448 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001449 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001450 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001451
1452 mVisibleRegionsDirty = true;
1453 invalidateHwcGeometry();
1454
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001455 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001456 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1457 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1458 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001459
Steven Thomasb02664d2017-07-26 18:48:28 -07001460 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001461 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001462 const nsecs_t period = activeConfig->getVsyncPeriod();
1463 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001464
Steven Thomasb02664d2017-07-26 18:48:28 -07001465 // Use phase of 0 since phase is not known.
1466 // Use latency of 0, which will snap to the ideal latency.
1467 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001468
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001469 android_atomic_or(1, &mRepaintEverything);
1470 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001471}
1472
Mathias Agopian4fec8732012-06-29 14:12:52 -07001473void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001474 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001475 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001476 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001477 bool frameMissed = !mHadClientComposition &&
1478 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001479 (mPreviousPresentFence->getSignalTime() ==
1480 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001481 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001482 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001483 mTimeStats.incrementMissedFrames();
1484 if (mPropagateBackpressure) {
1485 signalLayerUpdate();
1486 break;
1487 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001488 }
Dan Stoza50182882016-07-08 12:02:20 -07001489
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
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001787 mTimeStats.incrementTotalFrames();
1788 if (mHadClientComposition) {
1789 mTimeStats.incrementClientCompositionFrames();
1790 }
1791
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001792 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1793 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001794 return;
1795 }
1796
1797 nsecs_t currentTime = systemTime();
1798 if (mHasPoweredOff) {
1799 mHasPoweredOff = false;
1800 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001801 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001802 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001803 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1804 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001805 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001806 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001807 }
David Sodman4a36e932017-11-07 14:29:47 -08001808 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001809 }
David Sodman4a36e932017-11-07 14:29:47 -08001810 getBE().mLastSwapTime = currentTime;
Dan Stoza9fdb7e02018-06-21 12:10:12 -07001811
1812 {
1813 std::lock_guard lock(mTexturePoolMutex);
1814 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1815 if (refillCount > 0) {
1816 const size_t offset = mTexturePool.size();
1817 mTexturePool.resize(mTexturePoolSize);
1818 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1819 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1820 }
1821 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001822}
1823
1824void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001825 ATRACE_CALL();
1826 ALOGV("rebuildLayerStacks");
1827
Mathias Agopiancd60f992012-08-16 16:28:27 -07001828 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001829 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001830 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001831 mVisibleRegionsDirty = false;
1832 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001833
Jeff Sharkey76488112017-02-27 14:15:18 -07001834 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1835 Region opaqueRegion;
1836 Region dirtyRegion;
1837 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001838 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001839 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1840 const Transform& tr(displayDevice->getTransform());
1841 const Rect bounds(displayDevice->getBounds());
1842 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001843 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001844
Jeff Sharkey76488112017-02-27 14:15:18 -07001845 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001846 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001847 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1848 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001849 Region drawRegion(tr.transform(
1850 layer->visibleNonTransparentRegion));
1851 drawRegion.andSelf(bounds);
1852 if (!drawRegion.isEmpty()) {
1853 layersSortedByZ.add(layer);
1854 } else {
1855 // Clear out the HWC layer if this layer was
1856 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001857 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001858 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001859 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001860 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001861 // WM changes displayDevice->layerStack upon sleep/awake.
1862 // Here we make sure we delete the HWC layers even if
1863 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001864 hwcLayerDestroyed = layer->destroyHwcLayer(
1865 displayDevice->getHwcDisplayId());
1866 }
1867
1868 // If a layer is not going to get a release fence because
1869 // it is invisible, but it is also going to release its
1870 // old buffer, add it to the list of layers needing
1871 // fences.
1872 if (hwcLayerDestroyed) {
1873 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1874 mLayersWithQueuedFrames.cend(), layer);
1875 if (found != mLayersWithQueuedFrames.cend()) {
1876 layersNeedingFences.add(layer);
1877 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001878 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001879 });
1880 }
1881 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001882 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001883 displayDevice->undefinedRegion.set(bounds);
1884 displayDevice->undefinedRegion.subtractSelf(
1885 tr.transform(opaqueRegion));
1886 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001887 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001888 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001889}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001890
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001891// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001892// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001893// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001894// - Dataspace::DISPLAY_P3
1895// - Dataspace::V0_SCRGB_LINEAR
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001896// The returned HDR data space is one of
1897// - Dataspace::UNKNOWN
1898// - Dataspace::BT2020_HLG
1899// - Dataspace::BT2020_PQ
1900Dataspace SurfaceFlinger::getBestDataspace(
1901 const sp<const DisplayDevice>& displayDevice, Dataspace* outHdrDataSpace) const {
1902 Dataspace bestDataSpace = Dataspace::SRGB;
1903 *outHdrDataSpace = Dataspace::UNKNOWN;
1904
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001905 for (const auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1906 switch (layer->getDataSpace()) {
1907 case Dataspace::V0_SCRGB:
1908 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001909 bestDataSpace = Dataspace::V0_SCRGB_LINEAR;
Peiyong Linf59a7192018-04-25 11:19:31 -07001910 break;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001911 case Dataspace::DISPLAY_P3:
1912 if (bestDataSpace == Dataspace::SRGB) {
1913 bestDataSpace = Dataspace::DISPLAY_P3;
1914 }
1915 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001916 case Dataspace::BT2020_PQ:
1917 case Dataspace::BT2020_ITU_PQ:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001918 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001919 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001920 case Dataspace::BT2020_HLG:
1921 case Dataspace::BT2020_ITU_HLG:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001922 // When there's mixed PQ content and HLG content, we set the HDR
1923 // data space to be BT2020_PQ and convert HLG to PQ.
1924 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1925 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001926 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001927 break;
1928 default:
1929 break;
1930 }
Romain Guy54f154a2017-10-24 21:40:32 +01001931 }
1932
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001933 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001934}
1935
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001936// Pick the ColorMode / Dataspace for the display device.
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001937void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& displayDevice,
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001938 ColorMode* outMode, Dataspace* outDataSpace,
1939 RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001940 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1941 *outMode = ColorMode::NATIVE;
1942 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001943 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001944 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001945 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001946
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001947 Dataspace hdrDataSpace;
1948 Dataspace bestDataSpace = getBestDataspace(displayDevice, &hdrDataSpace);
1949
1950 if (hdrDataSpace == Dataspace::BT2020_PQ) {
1951 // Hardware composer can handle BT2100 ColorMode only when
1952 // - colorimetrical tone mapping is supported, or
1953 // - Auto mode is turned on and enhanced tone mapping is supported.
1954 if (displayDevice->hasBT2100PQColorimetricSupport() ||
1955 (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
1956 displayDevice->hasBT2100PQEnhanceSupport())) {
1957 *outMode = ColorMode::BT2100_PQ;
1958 *outDataSpace = Dataspace::BT2020_PQ;
1959 } else if (displayDevice->hasHDR10Support()) {
1960 // Legacy HDR support. HDR layers are treated as UNKNOWN layers.
1961 hdrDataSpace = Dataspace::UNKNOWN;
1962 } else {
1963 // Simulate PQ through RenderEngine, pick DISPLAY_P3 color mode.
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001964 *outMode = ColorMode::DISPLAY_P3;
1965 *outDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001966 }
1967 } else if (hdrDataSpace == Dataspace::BT2020_HLG) {
1968 if (displayDevice->hasBT2100HLGColorimetricSupport() ||
1969 (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
1970 displayDevice->hasBT2100HLGEnhanceSupport())) {
1971 *outMode = ColorMode::BT2100_HLG;
1972 *outDataSpace = Dataspace::BT2020_HLG;
1973 } else if (displayDevice->hasHLGSupport()) {
1974 // Legacy HDR support. HDR layers are treated as UNKNOWN layers.
1975 hdrDataSpace = Dataspace::UNKNOWN;
1976 } else {
1977 // Simulate HLG through RenderEngine, pick DISPLAY_P3 color mode.
1978 *outMode = ColorMode::DISPLAY_P3;
1979 *outDataSpace = Dataspace::DISPLAY_P3;
1980 }
1981 }
1982
1983 // At this point, there's no HDR layer.
1984 if (hdrDataSpace == Dataspace::UNKNOWN) {
1985 switch (bestDataSpace) {
1986 case Dataspace::DISPLAY_P3:
1987 case Dataspace::V0_SCRGB_LINEAR:
1988 *outMode = ColorMode::DISPLAY_P3;
1989 *outDataSpace = Dataspace::DISPLAY_P3;
1990 break;
1991 default:
1992 *outMode = ColorMode::SRGB;
1993 *outDataSpace = Dataspace::SRGB;
1994 break;
1995 }
1996 }
1997 *outRenderIntent = pickRenderIntent(displayDevice, *outMode);
1998}
1999
2000RenderIntent SurfaceFlinger::pickRenderIntent(const sp<DisplayDevice>& displayDevice,
2001 ColorMode colorMode) const {
2002 // Native Mode means the display is not color managed, and whichever
2003 // render intent is picked doesn't matter, thus return
2004 // RenderIntent::COLORIMETRIC as default here.
2005 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2006 return RenderIntent::COLORIMETRIC;
2007 }
2008
2009 // In Auto Color Mode, we want to strech to panel color space, right now
2010 // only the built-in display supports it.
2011 if (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
2012 mBuiltinDisplaySupportsEnhance &&
2013 displayDevice->getDisplayType() == DisplayDevice::DISPLAY_PRIMARY) {
2014 switch (colorMode) {
2015 case ColorMode::DISPLAY_P3:
2016 case ColorMode::SRGB:
2017 return RenderIntent::ENHANCE;
2018 // In Auto Color Mode, BT2100_PQ and BT2100_HLG will only be picked
2019 // when TONE_MAP_ENHANCE or TONE_MAP_COLORIMETRIC is supported.
2020 // If TONE_MAP_ENHANCE is not supported, fall back to TONE_MAP_COLORIMETRIC.
2021 case ColorMode::BT2100_PQ:
2022 return displayDevice->hasBT2100PQEnhanceSupport() ?
2023 RenderIntent::TONE_MAP_ENHANCE : RenderIntent::TONE_MAP_COLORIMETRIC;
2024 case ColorMode::BT2100_HLG:
2025 return displayDevice->hasBT2100HLGEnhanceSupport() ?
2026 RenderIntent::TONE_MAP_ENHANCE : RenderIntent::TONE_MAP_COLORIMETRIC;
2027 // This statement shouldn't be reached, switch cases will always
2028 // cover all possible ColorMode returned by pickColorMode.
2029 default:
2030 return RenderIntent::COLORIMETRIC;
2031 }
2032 }
2033
2034 // Either enhance is not supported or we are in natural mode.
2035
2036 // Natural Mode means it's color managed and the color must be right,
2037 // thus we pick RenderIntent::COLORIMETRIC as render intent for non-HDR
2038 // content and pick RenderIntent::TONE_MAP_COLORIMETRIC for HDR content.
2039 switch (colorMode) {
2040 // In Natural Color Mode, BT2100_PQ and BT2100_HLG will only be picked
2041 // when TONE_MAP_COLORIMETRIC is supported.
2042 case ColorMode::BT2100_PQ:
2043 case ColorMode::BT2100_HLG:
2044 return RenderIntent::TONE_MAP_COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002045 default:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002046 return RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002047 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002048}
2049
Mathias Agopiancd60f992012-08-16 16:28:27 -07002050void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002051 ATRACE_CALL();
2052 ALOGV("setUpHWComposer");
2053
Jesse Hall028dc8f2013-08-20 16:35:32 -07002054 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Dan Stozac7a25ad2018-04-12 11:45:09 -07002055 bool dirty = !mDisplays[dpy]->getDirtyRegion(mRepaintEverything).isEmpty();
Jesse Hallb7a05492014-08-14 15:45:06 -07002056 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
2057 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
2058
2059 // If nothing has changed (!dirty), don't recompose.
2060 // If something changed, but we don't currently have any visible layers,
2061 // and didn't when we last did a composition, then skip it this time.
2062 // The second rule does two things:
2063 // - When all layers are removed from a display, we'll emit one black
2064 // frame, then nothing more until we get new layers.
2065 // - When a display is created with a private layer stack, we won't
2066 // emit any black frames until a layer is added to the layer stack.
2067 bool mustRecompose = dirty && !(empty && wasEmpty);
2068
2069 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2070 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
2071 mustRecompose ? "doing" : "skipping",
2072 dirty ? "+" : "-",
2073 empty ? "+" : "-",
2074 wasEmpty ? "+" : "-");
2075
Dan Stoza71433162014-02-04 16:22:36 -08002076 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07002077
2078 if (mustRecompose) {
2079 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
2080 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07002081 }
2082
Dan Stoza9e56aa02015-11-02 13:00:03 -08002083 // build the h/w work list
2084 if (CC_UNLIKELY(mGeometryInvalid)) {
2085 mGeometryInvalid = false;
2086 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2087 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
2088 const auto hwcId = displayDevice->getHwcDisplayId();
2089 if (hwcId >= 0) {
2090 const Vector<sp<Layer>>& currentLayers(
2091 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08002092 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002093 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08002094 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07002095 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002096 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002097 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07002098 }
2099 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07002100
Robert Carrae060832016-11-28 10:51:00 -08002101 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002102 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002103 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07002104 }
2105 }
2106 }
2107 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002108 }
Riley Andrews03414a12014-07-01 14:22:59 -07002109
Dan Stoza9e56aa02015-11-02 13:00:03 -08002110 // Set the per-frame data
2111 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2112 auto& displayDevice = mDisplays[displayId];
2113 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002114
Dan Stoza9e56aa02015-11-02 13:00:03 -08002115 if (hwcId < 0) {
2116 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07002117 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07002118 if (mDrawingState.colorMatrixChanged) {
2119 displayDevice->setColorTransform(mDrawingState.colorMatrix);
2120 status_t result = getBE().mHwc->setColorTransform(hwcId, mDrawingState.colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002121 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
2122 "display %zd: %d", displayId, result);
2123 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002124 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002125 if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2126 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Peiyong Lin62665892018-04-16 11:07:44 -07002127 !displayDevice->hasHDR10Support()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002128 layer->forceClientComposition(hwcId);
2129 }
Peiyong Linf59a7192018-04-25 11:19:31 -07002130 if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
2131 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
2132 !displayDevice->hasHLGSupport()) {
2133 layer->forceClientComposition(hwcId);
2134 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002135
chaviwc9232ed2017-11-14 15:31:15 -08002136 if (layer->getForceClientComposition(hwcId)) {
2137 ALOGV("[%s] Requesting Client composition", layer->getName().string());
2138 layer->setCompositionType(hwcId, HWC2::Composition::Client);
2139 continue;
2140 }
2141
Dan Stoza9e56aa02015-11-02 13:00:03 -08002142 layer->setPerFrameData(displayDevice);
2143 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002144
2145 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002146 ColorMode colorMode;
2147 Dataspace dataSpace;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002148 RenderIntent renderIntent;
2149 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
2150 setActiveColorModeInternal(displayDevice, colorMode, dataSpace, renderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002151 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002152 }
2153
Chia-I Wu28f320b2018-05-03 11:02:56 -07002154 mDrawingState.colorMatrixChanged = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002155
Dan Stoza9e56aa02015-11-02 13:00:03 -08002156 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002157 auto& displayDevice = mDisplays[displayId];
2158 if (!displayDevice->isDisplayOn()) {
2159 continue;
2160 }
2161
David Sodman105b7dc2017-11-04 20:28:14 -07002162 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002163 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2164 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002165 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002166}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002167
Mathias Agopiancd60f992012-08-16 16:28:27 -07002168void SurfaceFlinger::doComposition() {
2169 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002170 ALOGV("doComposition");
2171
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002172 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002173 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002174 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002175 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002176 // transform the dirty region into this screen's coordinate space
2177 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002178
2179 // repaint the framebuffer (if needed)
2180 doDisplayComposition(hw, dirtyRegion);
2181
Mathias Agopiancd60f992012-08-16 16:28:27 -07002182 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002183 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002184 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002185 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002186 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002187}
2188
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002189void SurfaceFlinger::postFramebuffer()
2190{
Mathias Agopian841cde52012-03-01 15:44:37 -08002191 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002192 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002193
Mathias Agopiana44b0412011-10-16 18:46:35 -07002194 const nsecs_t now = systemTime();
2195 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002196
Dan Stoza9e56aa02015-11-02 13:00:03 -08002197 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2198 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002199 if (!displayDevice->isDisplayOn()) {
2200 continue;
2201 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002202 const auto hwcId = displayDevice->getHwcDisplayId();
2203 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002204 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002205 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002206 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002207 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002208 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002209 // The layer buffer from the previous frame (if any) is released
2210 // by HWC only when the release fence from this frame (if any) is
2211 // signaled. Always get the release fence from HWC first.
2212 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002213 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002214
2215 // If the layer was client composited in the previous frame, we
2216 // need to merge with the previous client target acquire fence.
2217 // Since we do not track that, always merge with the current
2218 // client target acquire fence when it is available, even though
2219 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002220 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002221 releaseFence = Fence::merge("LayerRelease", releaseFence,
2222 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002223 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002224
Dan Stoza9e56aa02015-11-02 13:00:03 -08002225 layer->onLayerDisplayed(releaseFence);
2226 }
Chia-I Wu83806892017-11-16 10:50:20 -08002227
2228 // We've got a list of layers needing fences, that are disjoint with
2229 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2230 // supply them with the present fence.
2231 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002232 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002233 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2234 layer->onLayerDisplayed(presentFence);
2235 }
2236 }
2237
Dan Stoza9e56aa02015-11-02 13:00:03 -08002238 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002239 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002240 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002241 }
2242
Mathias Agopiana44b0412011-10-16 18:46:35 -07002243 mLastSwapBufferTime = systemTime() - now;
2244 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002245
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002246 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002247 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2248 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2249 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2250 logFrameStats();
2251 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002252 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002253}
2254
Mathias Agopian87baae12012-07-31 12:38:26 -07002255void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002256{
Mathias Agopian841cde52012-03-01 15:44:37 -08002257 ATRACE_CALL();
2258
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002259 // here we keep a copy of the drawing state (that is the state that's
2260 // going to be overwritten by handleTransactionLocked()) outside of
2261 // mStateLock so that the side-effects of the State assignment
2262 // don't happen with mStateLock held (which can cause deadlocks).
2263 State drawingState(mDrawingState);
2264
Mathias Agopianca4d3602011-05-19 15:38:14 -07002265 Mutex::Autolock _l(mStateLock);
2266 const nsecs_t now = systemTime();
2267 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002268
Mathias Agopianca4d3602011-05-19 15:38:14 -07002269 // Here we're guaranteed that some transaction flags are set
2270 // so we can call handleTransactionLocked() unconditionally.
2271 // We call getTransactionFlags(), which will also clear the flags,
2272 // with mStateLock held to guarantee that mCurrentState won't change
2273 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002274
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002275 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002276 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002277 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002278
Mathias Agopianca4d3602011-05-19 15:38:14 -07002279 mLastTransactionTime = systemTime() - now;
2280 mDebugInTransaction = 0;
2281 invalidateHwcGeometry();
2282 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002283}
2284
Lloyd Pique715a2c12017-12-14 17:18:08 -08002285DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique09594832018-01-22 17:48:03 -08002286 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002287 // Figure out whether the event is for the primary display or an
2288 // external display by matching the Hwc display id against one for a
2289 // connected display. If we did not find a match, we then check what
2290 // displays are not already connected to determine the type. If we don't
2291 // have a connected primary display, we assume the new display is meant to
2292 // be the primary display, and then if we don't have an external display,
2293 // we assume it is that.
2294 const auto primaryDisplayId =
2295 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2296 const auto externalDisplayId =
2297 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2298 if (primaryDisplayId && primaryDisplayId == display) {
2299 return DisplayDevice::DISPLAY_PRIMARY;
2300 } else if (externalDisplayId && externalDisplayId == display) {
2301 return DisplayDevice::DISPLAY_EXTERNAL;
2302 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2303 return DisplayDevice::DISPLAY_PRIMARY;
2304 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2305 return DisplayDevice::DISPLAY_EXTERNAL;
2306 }
2307
2308 return DisplayDevice::DISPLAY_ID_INVALID;
2309}
2310
Lloyd Piqueba04e622017-12-14 17:11:26 -08002311void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2312 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002313 auto displayType = determineDisplayType(event.display, event.connection);
2314 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2315 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2316 continue;
2317 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002318
2319 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2320 ALOGE("External displays are not supported by the vr hardware composer.");
2321 continue;
2322 }
2323
Lloyd Pique715a2c12017-12-14 17:18:08 -08002324 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002325
2326 if (event.connection == HWC2::Connection::Connected) {
Steven Thomas3bed0522018-03-20 15:40:48 -07002327 if (!mBuiltinDisplays[displayType].get()) {
2328 ALOGV("Creating built in display %d", displayType);
2329 mBuiltinDisplays[displayType] = new BBinder();
2330 // All non-virtual displays are currently considered secure.
2331 DisplayDeviceState info(displayType, true);
2332 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2333 "Built-in Screen" : "External Screen";
2334 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
Lloyd Pique4d234852018-01-22 17:21:36 -08002335 mInterceptor->saveDisplayCreation(info);
Steven Thomas3bed0522018-03-20 15:40:48 -07002336 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002337 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002338 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002339
Lloyd Piquefcd86612017-12-14 17:15:36 -08002340 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2341 if (idx >= 0) {
2342 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Lloyd Pique4d234852018-01-22 17:21:36 -08002343 mInterceptor->saveDisplayDeletion(info.displayId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002344 mCurrentState.displays.removeItemsAt(idx);
2345 }
2346 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002347 }
2348
2349 processDisplayChangesLocked();
2350 }
2351
2352 mPendingHotplugEvents.clear();
2353}
2354
Lloyd Pique09594832018-01-22 17:48:03 -08002355sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2356 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2357 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002358 bool hasWideColorGamut = false;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002359 std::unordered_map<ColorMode, std::vector<RenderIntent>> hdrAndRenderIntents;
2360
Lloyd Pique09594832018-01-22 17:48:03 -08002361 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002362 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Lloyd Pique09594832018-01-22 17:48:03 -08002363 for (ColorMode colorMode : modes) {
2364 switch (colorMode) {
2365 case ColorMode::DISPLAY_P3:
2366 case ColorMode::ADOBE_RGB:
2367 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002368 hasWideColorGamut = true;
Lloyd Pique09594832018-01-22 17:48:03 -08002369 break;
2370 default:
2371 break;
2372 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002373
2374 std::vector<RenderIntent> renderIntents = getHwComposer().getRenderIntents(hwcId,
2375 colorMode);
2376 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2377 for (auto intent : renderIntents) {
2378 if (intent == RenderIntent::ENHANCE) {
2379 mBuiltinDisplaySupportsEnhance = true;
2380 break;
2381 }
2382 }
2383 }
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002384
2385 if (colorMode == ColorMode::BT2100_PQ || colorMode == ColorMode::BT2100_HLG) {
2386 hdrAndRenderIntents.emplace(colorMode, renderIntents);
2387 }
Lloyd Pique09594832018-01-22 17:48:03 -08002388 }
2389 }
2390
Peiyong Lin62665892018-04-16 11:07:44 -07002391 HdrCapabilities hdrCapabilities;
2392 getHwComposer().getHdrCapabilities(hwcId, &hdrCapabilities);
Lloyd Pique09594832018-01-22 17:48:03 -08002393
2394 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2395 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2396
2397 /*
2398 * Create our display's surface
2399 */
2400 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2401 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
2402 renderSurface->setAsync(state.type >= DisplayDevice::DISPLAY_VIRTUAL);
2403 renderSurface->setNativeWindow(nativeWindow.get());
2404 const int displayWidth = renderSurface->queryWidth();
2405 const int displayHeight = renderSurface->queryHeight();
2406
2407 // Make sure that composition can never be stalled by a virtual display
2408 // consumer that isn't processing buffers fast enough. We have to do this
2409 // in two places:
2410 // * Here, in case the display is composed entirely by HWC.
2411 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2412 // window's swap interval in eglMakeCurrent, so they'll override the
2413 // interval we set here.
2414 if (state.type >= DisplayDevice::DISPLAY_VIRTUAL) {
2415 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2416 }
2417
2418 // virtual displays are always considered enabled
2419 auto initialPowerMode = (state.type >= DisplayDevice::DISPLAY_VIRTUAL) ? HWC_POWER_MODE_NORMAL
2420 : HWC_POWER_MODE_OFF;
2421
2422 sp<DisplayDevice> hw =
2423 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2424 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
Peiyong Lin2c327ac2018-04-19 22:06:34 -07002425 hasWideColorGamut, hdrCapabilities,
2426 getHwComposer().getSupportedPerFrameMetadata(hwcId),
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002427 hdrAndRenderIntents, initialPowerMode);
Lloyd Pique09594832018-01-22 17:48:03 -08002428
2429 if (maxFrameBufferAcquiredBuffers >= 3) {
2430 nativeWindowSurface->preallocateBuffers();
2431 }
2432
2433 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002434 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2435 if (hasWideColorGamut) {
Lloyd Pique09594832018-01-22 17:48:03 -08002436 defaultColorMode = ColorMode::SRGB;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002437 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique09594832018-01-22 17:48:03 -08002438 }
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002439 setActiveColorModeInternal(hw, defaultColorMode, defaultDataSpace,
2440 RenderIntent::COLORIMETRIC);
Lloyd Pique09594832018-01-22 17:48:03 -08002441 hw->setLayerStack(state.layerStack);
2442 hw->setProjection(state.orientation, state.viewport, state.frame);
2443 hw->setDisplayName(state.displayName);
2444
2445 return hw;
2446}
2447
Lloyd Pique347200f2017-12-14 17:00:15 -08002448void SurfaceFlinger::processDisplayChangesLocked() {
2449 // here we take advantage of Vector's copy-on-write semantics to
2450 // improve performance by skipping the transaction entirely when
2451 // know that the lists are identical
2452 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2453 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2454 if (!curr.isIdenticalTo(draw)) {
2455 mVisibleRegionsDirty = true;
2456 const size_t cc = curr.size();
2457 size_t dc = draw.size();
2458
2459 // find the displays that were removed
2460 // (ie: in drawing state but not in current state)
2461 // also handle displays that changed
2462 // (ie: displays that are in both lists)
2463 for (size_t i = 0; i < dc;) {
2464 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2465 if (j < 0) {
2466 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002467 // Call makeCurrent() on the primary display so we can
2468 // be sure that nothing associated with this display
2469 // is current.
2470 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2471 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2472 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2473 if (hw != nullptr) hw->disconnect(getHwComposer());
2474 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2475 mEventThread->onHotplugReceived(draw[i].type, false);
2476 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002477 } else {
2478 // this display is in both lists. see if something changed.
2479 const DisplayDeviceState& state(curr[j]);
2480 const wp<IBinder>& display(curr.keyAt(j));
2481 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2482 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2483 if (state_binder != draw_binder) {
2484 // changing the surface is like destroying and
2485 // recreating the DisplayDevice, so we just remove it
2486 // from the drawing state, so that it get re-added
2487 // below.
2488 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2489 if (hw != nullptr) hw->disconnect(getHwComposer());
2490 mDisplays.removeItem(display);
2491 mDrawingState.displays.removeItemsAt(i);
2492 dc--;
2493 // at this point we must loop to the next item
2494 continue;
2495 }
2496
2497 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2498 if (disp != nullptr) {
2499 if (state.layerStack != draw[i].layerStack) {
2500 disp->setLayerStack(state.layerStack);
2501 }
2502 if ((state.orientation != draw[i].orientation) ||
2503 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2504 disp->setProjection(state.orientation, state.viewport, state.frame);
2505 }
2506 if (state.width != draw[i].width || state.height != draw[i].height) {
2507 disp->setDisplaySize(state.width, state.height);
2508 }
2509 }
2510 }
2511 ++i;
2512 }
2513
2514 // find displays that were added
2515 // (ie: in current state but not in drawing state)
2516 for (size_t i = 0; i < cc; i++) {
2517 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2518 const DisplayDeviceState& state(curr[i]);
2519
2520 sp<DisplaySurface> dispSurface;
2521 sp<IGraphicBufferProducer> producer;
2522 sp<IGraphicBufferProducer> bqProducer;
2523 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002524 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002525
2526 int32_t hwcId = -1;
2527 if (state.isVirtualDisplay()) {
2528 // Virtual displays without a surface are dormant:
2529 // they have external state (layer stack, projection,
2530 // etc.) but no internal state (i.e. a DisplayDevice).
2531 if (state.surface != nullptr) {
2532 // Allow VR composer to use virtual displays.
2533 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2534 int width = 0;
2535 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2536 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2537 int height = 0;
2538 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2539 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2540 int intFormat = 0;
2541 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2542 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002543 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002544
2545 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2546 }
2547
2548 // TODO: Plumb requested format back up to consumer
2549
2550 sp<VirtualDisplaySurface> vds =
2551 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2552 bqProducer, bqConsumer,
2553 state.displayName);
2554
2555 dispSurface = vds;
2556 producer = vds;
2557 }
2558 } else {
2559 ALOGE_IF(state.surface != nullptr,
2560 "adding a supported display, but rendering "
2561 "surface is provided (%p), ignoring it",
2562 state.surface.get());
2563
2564 hwcId = state.type;
2565 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2566 producer = bqProducer;
2567 }
2568
2569 const wp<IBinder>& display(curr.keyAt(i));
2570 if (dispSurface != nullptr) {
Lloyd Pique09594832018-01-22 17:48:03 -08002571 mDisplays.add(display,
2572 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2573 producer));
Lloyd Pique347200f2017-12-14 17:00:15 -08002574 if (!state.isVirtualDisplay()) {
2575 mEventThread->onHotplugReceived(state.type, true);
2576 }
2577 }
2578 }
2579 }
2580 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002581
2582 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002583}
2584
Mathias Agopian87baae12012-07-31 12:38:26 -07002585void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002586{
Dan Stoza7dde5992015-05-22 09:51:44 -07002587 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002588 mCurrentState.traverseInZOrder([](Layer* layer) {
2589 layer->notifyAvailableFrames();
2590 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002591
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002592 /*
2593 * Traversal of the children
2594 * (perform the transaction for each of them if needed)
2595 */
2596
Mathias Agopian3559b072012-08-15 13:46:03 -07002597 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002598 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002599 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002600 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002601
2602 const uint32_t flags = layer->doTransaction(0);
2603 if (flags & Layer::eVisibleRegion)
2604 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002605 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002606 }
2607
2608 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002609 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002610 */
2611
Mathias Agopiane57f2922012-08-09 16:29:12 -07002612 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002613 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002614 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002615 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002616
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002617 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002618 // The transform hint might have changed for some layers
2619 // (either because a display has changed, or because a layer
2620 // as changed).
2621 //
2622 // Walk through all the layers in currentLayers,
2623 // and update their transform hint.
2624 //
2625 // If a layer is visible only on a single display, then that
2626 // display is used to calculate the hint, otherwise we use the
2627 // default display.
2628 //
2629 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2630 // the hint is set before we acquire a buffer from the surface texture.
2631 //
2632 // NOTE: layer transactions have taken place already, so we use their
2633 // drawing state. However, SurfaceFlinger's own transaction has not
2634 // happened yet, so we must use the current state layer list
2635 // (soon to become the drawing state list).
2636 //
2637 sp<const DisplayDevice> disp;
2638 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002639 bool first = true;
2640 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002641 // NOTE: we rely on the fact that layers are sorted by
2642 // layerStack first (so we don't have to traverse the list
2643 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002644 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002645 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002646 currentlayerStack = layerStack;
2647 // figure out if this layerstack is mirrored
2648 // (more than one display) if so, pick the default display,
2649 // if not, pick the only display it's on.
2650 disp.clear();
2651 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2652 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002653 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002654 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002655 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002656 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002657 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002658 break;
2659 }
2660 }
2661 }
2662 }
Chet Haase91d25932013-04-11 15:24:55 -07002663
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002664 if (disp == nullptr) {
2665 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2666 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002667
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002668 // could be null when this layer is using a layerStack
2669 // that is not visible on any display. Also can occur at
2670 // screen off/on times.
2671 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002672 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002673
2674 // disp can be null if there is no display available at all to get
2675 // the transform hint from.
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002676 if (disp != nullptr) {
2677 layer->updateTransformHint(disp);
2678 }
Robert Carr2047fae2016-11-28 14:09:09 -08002679
2680 first = false;
2681 });
Mathias Agopian84300952012-11-21 16:02:13 -08002682 }
2683
2684
Mathias Agopian3559b072012-08-15 13:46:03 -07002685 /*
2686 * Perform our own transaction if needed
2687 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002688
2689 if (mLayersAdded) {
2690 mLayersAdded = false;
2691 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002692 mVisibleRegionsDirty = true;
2693 }
2694
2695 // some layers might have been removed, so
2696 // we need to update the regions they're exposing.
2697 if (mLayersRemoved) {
2698 mLayersRemoved = false;
2699 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002700 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002701 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002702 // this layer is not visible anymore
2703 // TODO: we could traverse the tree from front to back and
2704 // compute the actual visible region
2705 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002706 Region visibleReg;
2707 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002708 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002709 }
Robert Carr2047fae2016-11-28 14:09:09 -08002710 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002711 }
2712
2713 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002714
2715 updateCursorAsync();
2716}
2717
2718void SurfaceFlinger::updateCursorAsync()
2719{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002720 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2721 auto& displayDevice = mDisplays[displayId];
2722 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002723 continue;
2724 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002725
2726 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2727 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002728 }
2729 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002730}
2731
2732void SurfaceFlinger::commitTransaction()
2733{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002734 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002735 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002736 for (const auto& l : mLayersPendingRemoval) {
2737 recordBufferingStats(l->getName().string(),
2738 l->getOccupancyHistory(true));
2739 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002740 }
2741 mLayersPendingRemoval.clear();
2742 }
2743
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002744 // If this transaction is part of a window animation then the next frame
2745 // we composite should be considered an animation as well.
2746 mAnimCompositionPending = mAnimTransactionPending;
2747
Mathias Agopian4fec8732012-06-29 14:12:52 -07002748 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002749 // clear the "changed" flags in current state
2750 mCurrentState.colorMatrixChanged = false;
2751
Robert Carr1f0a16a2016-10-24 16:27:39 -07002752 mDrawingState.traverseInZOrder([](Layer* layer) {
2753 layer->commitChildList();
2754 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002755 mTransactionPending = false;
2756 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002757 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002758}
2759
Chia-I Wuab0c3192017-08-01 11:29:00 -07002760void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002761 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002762{
Mathias Agopian841cde52012-03-01 15:44:37 -08002763 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002764 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002765
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002766 Region aboveOpaqueLayers;
2767 Region aboveCoveredLayers;
2768 Region dirty;
2769
Mathias Agopian87baae12012-07-31 12:38:26 -07002770 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002771
Robert Carr2047fae2016-11-28 14:09:09 -08002772 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002773 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002774 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002775
Jesse Hall01e29052013-02-19 16:13:35 -08002776 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002777 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002778 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002779
Mathias Agopianab028732010-03-16 16:41:46 -07002780 /*
2781 * opaqueRegion: area of a surface that is fully opaque.
2782 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002783 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002784
2785 /*
2786 * visibleRegion: area of a surface that is visible on screen
2787 * and not fully transparent. This is essentially the layer's
2788 * footprint minus the opaque regions above it.
2789 * Areas covered by a translucent surface are considered visible.
2790 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002791 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002792
2793 /*
2794 * coveredRegion: area of a surface that is covered by all
2795 * visible regions above it (which includes the translucent areas).
2796 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002797 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002798
Jesse Halla8026d22012-09-25 13:25:04 -07002799 /*
2800 * transparentRegion: area of a surface that is hinted to be completely
2801 * transparent. This is only used to tell when the layer has no visible
2802 * non-transparent regions and can be removed from the layer list. It
2803 * does not affect the visibleRegion of this layer or any layers
2804 * beneath it. The hint may not be correct if apps don't respect the
2805 * SurfaceView restrictions (which, sadly, some don't).
2806 */
2807 Region transparentRegion;
2808
Mathias Agopianab028732010-03-16 16:41:46 -07002809
2810 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002811 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002812 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002813 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002814 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002815 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002816 if (!visibleRegion.isEmpty()) {
2817 // Remove the transparent area from the visible region
2818 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002819 if (tr.preserveRects()) {
2820 // transform the transparent region
2821 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002822 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002823 // transformation too complex, can't do the
2824 // transparent region optimization.
2825 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002826 }
Mathias Agopianab028732010-03-16 16:41:46 -07002827 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002828
Mathias Agopianab028732010-03-16 16:41:46 -07002829 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002830 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002831 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002832 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2833 // the opaque region is the layer's footprint
2834 opaqueRegion = visibleRegion;
2835 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002836 }
2837 }
2838
Robert Carre5f4f692018-01-12 13:12:28 -08002839 if (visibleRegion.isEmpty()) {
2840 layer->clearVisibilityRegions();
2841 return;
2842 }
2843
Mathias Agopianab028732010-03-16 16:41:46 -07002844 // Clip the covered region to the visible region
2845 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2846
2847 // Update aboveCoveredLayers for next (lower) layer
2848 aboveCoveredLayers.orSelf(visibleRegion);
2849
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002850 // subtract the opaque region covered by the layers above us
2851 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002852
2853 // compute this layer's dirty region
2854 if (layer->contentDirty) {
2855 // we need to invalidate the whole region
2856 dirty = visibleRegion;
2857 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002858 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002859 layer->contentDirty = false;
2860 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002861 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002862 * the exposed region consists of two components:
2863 * 1) what's VISIBLE now and was COVERED before
2864 * 2) what's EXPOSED now less what was EXPOSED before
2865 *
2866 * note that (1) is conservative, we start with the whole
2867 * visible region but only keep what used to be covered by
2868 * something -- which mean it may have been exposed.
2869 *
2870 * (2) handles areas that were not covered by anything but got
2871 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002872 */
Mathias Agopianab028732010-03-16 16:41:46 -07002873 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002874 const Region oldVisibleRegion = layer->visibleRegion;
2875 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002876 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2877 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002878 }
2879 dirty.subtractSelf(aboveOpaqueLayers);
2880
2881 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002882 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002883
Mathias Agopianab028732010-03-16 16:41:46 -07002884 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002885 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002886
Jesse Halla8026d22012-09-25 13:25:04 -07002887 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002888 layer->setVisibleRegion(visibleRegion);
2889 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002890 layer->setVisibleNonTransparentRegion(
2891 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002892 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002893
Mathias Agopian87baae12012-07-31 12:38:26 -07002894 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002895}
2896
Chia-I Wuab0c3192017-08-01 11:29:00 -07002897void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002898 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002899 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002900 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002901 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002902 }
2903 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002904}
2905
Dan Stoza6b9454d2014-11-07 16:00:59 -08002906bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002907{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002908 ALOGV("handlePageFlip");
2909
Brian Andersond6927fb2016-07-23 23:37:30 -07002910 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002911
Mathias Agopian4fec8732012-06-29 14:12:52 -07002912 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002913 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002914 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002915
2916 // Store the set of layers that need updates. This set must not change as
2917 // buffers are being latched, as this could result in a deadlock.
2918 // Example: Two producers share the same command stream and:
2919 // 1.) Layer 0 is latched
2920 // 2.) Layer 0 gets a new frame
2921 // 2.) Layer 1 gets a new frame
2922 // 3.) Layer 1 is latched.
2923 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2924 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002925 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002926 if (layer->hasQueuedFrame()) {
2927 frameQueued = true;
2928 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002929 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002930 } else {
2931 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002932 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002933 } else {
2934 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002935 }
Robert Carr2047fae2016-11-28 14:09:09 -08002936 });
2937
Dan Stoza9e56aa02015-11-02 13:00:03 -08002938 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002939 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002940 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002941 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002942 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002943 newDataLatched = true;
2944 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002945 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002946
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002947 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002948
2949 // If we will need to wake up at some time in the future to deal with a
2950 // queued frame that shouldn't be displayed during this vsync period, wake
2951 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002952 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002953 signalLayerUpdate();
2954 }
2955
2956 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002957 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002958}
2959
Mathias Agopianad456f92011-01-13 17:53:01 -08002960void SurfaceFlinger::invalidateHwcGeometry()
2961{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002962 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002963}
2964
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002965
Fabien Sanglard830b8472016-11-30 16:35:58 -08002966void SurfaceFlinger::doDisplayComposition(
2967 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002968 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002969{
Dan Stoza71433162014-02-04 16:22:36 -08002970 // We only need to actually compose the display if:
2971 // 1) It is being handled by hardware composer, which may need this to
2972 // keep its virtual display state machine in sync, or
2973 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002974 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002975 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002976 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002977 return;
2978 }
2979
Dan Stoza9e56aa02015-11-02 13:00:03 -08002980 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002981 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002982
2983 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002984 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002985}
2986
Chia-I Wub02087d2017-11-09 10:19:54 -08002987bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002988{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002989 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002990
Chia-I Wub02087d2017-11-09 10:19:54 -08002991 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002992 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002993 const auto hwcId = displayDevice->getHwcDisplayId();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002994 const bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002995 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002996
Chia-I Wu8e50e692018-05-04 10:12:37 -07002997 bool applyColorMatrix = false;
2998 bool applyLegacyColorMatrix = false;
2999 mat4 colorMatrix;
3000 mat4 legacyColorMatrix;
3001 const mat4* currentColorMatrix = nullptr;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003002
Dan Stoza9e56aa02015-11-02 13:00:03 -08003003 if (hasClientComposition) {
3004 ALOGV("hasClientComposition");
3005
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003006 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003007 if (displayDevice->hasWideColorGamut()) {
3008 outputDataspace = displayDevice->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003009 }
3010 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003011 getBE().mRenderEngine->setDisplayMaxLuminance(
3012 displayDevice->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003013
Chia-I Wu8e50e692018-05-04 10:12:37 -07003014 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
3015 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
3016 HWC2::Capability::SkipClientColorTransform);
3017
3018 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3019 if (applyColorMatrix) {
3020 colorMatrix = mDrawingState.colorMatrix;
3021 }
3022
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07003023 applyLegacyColorMatrix = (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
3024 outputDataspace != Dataspace::UNKNOWN &&
3025 outputDataspace != Dataspace::SRGB);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003026 if (applyLegacyColorMatrix) {
3027 if (applyColorMatrix) {
3028 legacyColorMatrix = colorMatrix * mLegacySrgbSaturationMatrix;
3029 } else {
3030 legacyColorMatrix = mLegacySrgbSaturationMatrix;
3031 }
3032 }
3033
Chia-I Wu7f402902017-11-09 12:51:10 -08003034 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003035 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003036 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08003037 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003038
3039 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08003040 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07003041 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
3042 }
3043 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003044 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003045
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003046 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003047 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003048 // when using overlays, we assume a fully transparent framebuffer
3049 // NOTE: we could reduce how much we need to clear, for instance
3050 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003051 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003052 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003053 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003054 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003055 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003056 // we're left with the letterbox region
3057 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08003058 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07003059
3060 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08003061 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07003062
Mathias Agopianb9494d52012-04-18 02:28:45 -07003063 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003064 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003065 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08003066 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003067 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003068 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003069
Dan Stoza9e56aa02015-11-02 13:00:03 -08003070 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07003071 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07003072 // scissor on the main display. It should never be needed
3073 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08003074 const Rect& bounds(displayDevice->getBounds());
3075 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003076 if (scissor != bounds) {
3077 // scissor doesn't match the screen's dimensions, so we
3078 // need to clear everything outside of it and enable
3079 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003080
Mathias Agopianf45c5102012-10-24 16:29:17 -07003081 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08003082 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08003083 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07003084 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003085 }
3086 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003087 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003088
Mathias Agopian85d751c2012-08-29 16:59:24 -07003089 /*
3090 * and then, render the layers targeted at the framebuffer
3091 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003092
Dan Stoza9e56aa02015-11-02 13:00:03 -08003093 ALOGV("Rendering client layers");
3094 const Transform& displayTransform = displayDevice->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003095 bool firstLayer = true;
3096 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
3097 const Region clip(bounds.intersect(
3098 displayTransform.transform(layer->visibleRegion)));
3099 ALOGV("Layer: %s", layer->getName().string());
3100 ALOGV(" Composition type: %s",
3101 to_string(layer->getCompositionType(hwcId)).c_str());
3102 if (!clip.isEmpty()) {
3103 switch (layer->getCompositionType(hwcId)) {
3104 case HWC2::Composition::Cursor:
3105 case HWC2::Composition::Device:
3106 case HWC2::Composition::Sideband:
3107 case HWC2::Composition::SolidColor: {
3108 const Layer::State& state(layer->getDrawingState());
3109 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
3110 layer->isOpaque(state) && (state.color.a == 1.0f)
3111 && hasClientComposition) {
3112 // never clear the very first layer since we're
3113 // guaranteed the FB is already cleared
3114 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003115 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003116 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003117 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003118 case HWC2::Composition::Client: {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003119 // switch color matrices lazily
3120 if (layer->isLegacyDataSpace()) {
3121 if (applyLegacyColorMatrix && currentColorMatrix != &legacyColorMatrix) {
Peiyong Lind6fa4a72018-04-17 15:09:44 -07003122 // TODO(b/78891890) Legacy sRGB saturation matrix should be set
3123 // separately.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003124 getRenderEngine().setupColorTransform(legacyColorMatrix);
3125 currentColorMatrix = &legacyColorMatrix;
3126 }
3127 } else {
3128 if (applyColorMatrix && currentColorMatrix != &colorMatrix) {
3129 getRenderEngine().setupColorTransform(colorMatrix);
3130 currentColorMatrix = &colorMatrix;
3131 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003132 }
Chia-I Wu8e50e692018-05-04 10:12:37 -07003133
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003134 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003135 break;
3136 }
3137 default:
3138 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003139 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003140 } else {
3141 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003142 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003143 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003144 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003145
Chia-I Wu8e50e692018-05-04 10:12:37 -07003146 if (applyColorMatrix || applyLegacyColorMatrix) {
3147 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003148 }
3149
Mathias Agopianf45c5102012-10-24 16:29:17 -07003150 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003151 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003152 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003153}
3154
Fabien Sanglard830b8472016-11-30 16:35:58 -08003155void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
3156 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003157 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003158 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003159}
3160
Dan Stoza7d89d062015-04-30 13:29:25 -07003161status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003162 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003163 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003164 const sp<Layer>& lbc,
3165 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003166{
Dan Stoza7d89d062015-04-30 13:29:25 -07003167 // add this layer to the current state list
3168 {
3169 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003170 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003171 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3172 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003173 return NO_MEMORY;
3174 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003175 if (parent == nullptr) {
3176 mCurrentState.layersSortedByZ.add(lbc);
3177 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003178 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003179 ALOGE("addClientLayer called with a removed parent");
3180 return NAME_NOT_FOUND;
3181 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003182 parent->addChild(lbc);
3183 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003184
Dan Stoza101d8dc2018-02-27 15:42:25 -08003185 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
Dan Stoza0a0158c2018-03-16 13:38:54 -07003186 // TODO (b/74616334): Change this back to a fatal assert once the leak is fixed
3187 ALOGE_IF(mGraphicBufferProducerList.size() > mMaxGraphicBufferProducerListSize,
3188 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3189 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize,
3190 mNumLayers);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003191 mLayersAdded = true;
3192 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003193 }
3194
Mathias Agopian96f08192010-06-02 23:28:45 -07003195 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003196 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003197
Dan Stoza7d89d062015-04-30 13:29:25 -07003198 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003199}
3200
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003201status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003202 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003203 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3204}
Robert Carr7f9b8992017-03-10 11:08:39 -08003205
chaviwca27f252018-02-06 16:46:39 -08003206status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3207 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003208 if (layer->isPendingRemoval()) {
3209 return NO_ERROR;
3210 }
3211
Robert Carr1f0a16a2016-10-24 16:27:39 -07003212 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003213 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003214 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003215 if (topLevelOnly) {
3216 return NO_ERROR;
3217 }
3218
Chia-I Wu98f1c102017-05-30 14:54:08 -07003219 sp<Layer> ancestor = p;
3220 while (ancestor->getParent() != nullptr) {
3221 ancestor = ancestor->getParent();
3222 }
3223 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3224 ALOGE("removeLayer called with a layer whose parent has been removed");
3225 return NAME_NOT_FOUND;
3226 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003227
3228 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003229 } else {
3230 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003231 }
3232
Robert Carr136e2f62017-02-08 17:54:29 -08003233 // As a matter of normal operation, the LayerCleaner will produce a second
3234 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3235 // so we will succeed in promoting it, but it's already been removed
3236 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3237 // otherwise something has gone wrong and we are leaking the layer.
3238 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003239 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3240 layer->getName().string(),
3241 (p != nullptr) ? p->getName().string() : "no-parent");
3242 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003243 } else if (index < 0) {
3244 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003245 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003246
Chia-I Wuc6657022017-08-15 11:18:17 -07003247 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003248 mLayersPendingRemoval.add(layer);
3249 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003250 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003251 setTransactionFlags(eTransactionNeeded);
3252 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003253}
3254
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003255uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003256 return android_atomic_release_load(&mTransactionFlags);
3257}
3258
Mathias Agopian3f844832013-08-07 21:24:32 -07003259uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003260 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3261}
3262
Mathias Agopian3f844832013-08-07 21:24:32 -07003263uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza2713c302018-03-28 17:07:36 -07003264 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3265}
3266
3267uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3268 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003269 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza2713c302018-03-28 17:07:36 -07003270 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003271 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003272 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003273 }
3274 return old;
3275}
3276
chaviwca27f252018-02-06 16:46:39 -08003277bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3278 for (const ComposerState& state : states) {
3279 // Here we need to check that the interface we're given is indeed
3280 // one of our own. A malicious client could give us a nullptr
3281 // IInterface, or one of its own or even one of our own but a
3282 // different type. All these situations would cause us to crash.
3283 if (state.client == nullptr) {
3284 return true;
3285 }
3286
3287 sp<IBinder> binder = IInterface::asBinder(state.client);
3288 if (binder == nullptr) {
3289 return true;
3290 }
3291
3292 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3293 return true;
3294 }
3295 }
3296 return false;
3297}
3298
Mathias Agopian8b33f032012-07-24 20:43:54 -07003299void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003300 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003301 const Vector<DisplayState>& displays,
3302 uint32_t flags)
3303{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003304 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003305 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003306 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003307
chaviwca27f252018-02-06 16:46:39 -08003308 if (containsAnyInvalidClientState(states)) {
3309 return;
3310 }
3311
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003312 if (flags & eAnimation) {
3313 // For window updates that are part of an animation we must wait for
3314 // previous animation "frames" to be handled.
3315 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003316 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003317 if (CC_UNLIKELY(err != NO_ERROR)) {
3318 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003319 // caller after a few seconds.
3320 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3321 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003322 mAnimTransactionPending = false;
3323 break;
3324 }
3325 }
3326 }
3327
chaviwca27f252018-02-06 16:46:39 -08003328 for (const DisplayState& display : displays) {
3329 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003330 }
3331
chaviwca27f252018-02-06 16:46:39 -08003332 for (const ComposerState& state : states) {
3333 transactionFlags |= setClientStateLocked(state);
3334 }
3335
3336 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3337 // as destroyed should only occur after setting all other states. This is to allow for a
3338 // child re-parent to happen before marking its original parent as destroyed (which would
3339 // then mark the child as destroyed).
3340 for (const ComposerState& state : states) {
3341 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003342 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003343
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003344 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3345 // anyway. This can be used as a flush mechanism for previous async transactions.
3346 // Empty animation transaction can be used to simulate back-pressure, so also force a
3347 // transaction for empty animation transactions.
3348 if (transactionFlags == 0 &&
3349 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003350 transactionFlags = eTransactionNeeded;
3351 }
3352
Mathias Agopian386aa982011-11-07 21:58:03 -08003353 if (transactionFlags) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003354 if (mInterceptor->isEnabled()) {
3355 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003356 }
Irvel468051e2016-06-13 16:44:44 -07003357
Mathias Agopian386aa982011-11-07 21:58:03 -08003358 // this triggers the transaction
Dan Stoza2713c302018-03-28 17:07:36 -07003359 const auto start = (flags & eEarlyWakeup)
3360 ? VSyncModulator::TransactionStart::EARLY
3361 : VSyncModulator::TransactionStart::NORMAL;
3362 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003363
3364 // if this is a synchronous transaction, wait for it to take effect
3365 // before returning.
3366 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003367 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003368 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003369 if (flags & eAnimation) {
3370 mAnimTransactionPending = true;
3371 }
3372 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003373 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3374 if (CC_UNLIKELY(err != NO_ERROR)) {
3375 // just in case something goes wrong in SF, return to the
3376 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003377 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3378 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003379 break;
3380 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003381 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003382 }
3383}
3384
Mathias Agopiane57f2922012-08-09 16:29:12 -07003385uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3386{
Jesse Hall9a143922012-10-04 16:29:19 -07003387 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3388 if (dpyIdx < 0)
3389 return 0;
3390
Mathias Agopiane57f2922012-08-09 16:29:12 -07003391 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003392 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003393 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003394 const uint32_t what = s.what;
3395 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003396 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003397 disp.surface = s.surface;
3398 flags |= eDisplayTransactionNeeded;
3399 }
3400 }
3401 if (what & DisplayState::eLayerStackChanged) {
3402 if (disp.layerStack != s.layerStack) {
3403 disp.layerStack = s.layerStack;
3404 flags |= eDisplayTransactionNeeded;
3405 }
3406 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003407 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003408 if (disp.orientation != s.orientation) {
3409 disp.orientation = s.orientation;
3410 flags |= eDisplayTransactionNeeded;
3411 }
3412 if (disp.frame != s.frame) {
3413 disp.frame = s.frame;
3414 flags |= eDisplayTransactionNeeded;
3415 }
3416 if (disp.viewport != s.viewport) {
3417 disp.viewport = s.viewport;
3418 flags |= eDisplayTransactionNeeded;
3419 }
3420 }
Michael Lentine47e45402014-07-18 15:34:25 -07003421 if (what & DisplayState::eDisplaySizeChanged) {
3422 if (disp.width != s.width) {
3423 disp.width = s.width;
3424 flags |= eDisplayTransactionNeeded;
3425 }
3426 if (disp.height != s.height) {
3427 disp.height = s.height;
3428 flags |= eDisplayTransactionNeeded;
3429 }
3430 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003431 }
3432 return flags;
3433}
3434
chaviwca27f252018-02-06 16:46:39 -08003435uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3436 const layer_state_t& s = composerState.state;
3437 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3438
Mathias Agopian13127d82013-03-05 17:47:11 -08003439 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003440 if (layer == nullptr) {
3441 return 0;
3442 }
3443
3444 if (layer->isPendingRemoval()) {
3445 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3446 return 0;
3447 }
3448
3449 uint32_t flags = 0;
3450
3451 const uint32_t what = s.what;
3452 bool geometryAppliesWithResize =
3453 what & layer_state_t::eGeometryAppliesWithResize;
3454 if (what & layer_state_t::ePositionChanged) {
3455 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3456 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003457 }
chaviw8b3871a2017-11-01 17:41:01 -07003458 }
3459 if (what & layer_state_t::eLayerChanged) {
3460 // NOTE: index needs to be calculated before we update the state
3461 const auto& p = layer->getParent();
3462 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003463 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003464 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003465 mCurrentState.layersSortedByZ.removeAt(idx);
3466 mCurrentState.layersSortedByZ.add(layer);
3467 // we need traversal (state changed)
3468 // AND transaction (list changed)
3469 flags |= eTransactionNeeded|eTraversalNeeded;
3470 }
chaviw8b3871a2017-11-01 17:41:01 -07003471 } else {
3472 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003473 flags |= eTransactionNeeded|eTraversalNeeded;
3474 }
3475 }
chaviw8b3871a2017-11-01 17:41:01 -07003476 }
3477 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003478 // NOTE: index needs to be calculated before we update the state
3479 const auto& p = layer->getParent();
3480 if (p == nullptr) {
3481 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3482 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3483 mCurrentState.layersSortedByZ.removeAt(idx);
3484 mCurrentState.layersSortedByZ.add(layer);
3485 // we need traversal (state changed)
3486 // AND transaction (list changed)
3487 flags |= eTransactionNeeded|eTraversalNeeded;
3488 }
3489 } else {
3490 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3491 flags |= eTransactionNeeded|eTraversalNeeded;
3492 }
chaviw8b3871a2017-11-01 17:41:01 -07003493 }
3494 }
3495 if (what & layer_state_t::eSizeChanged) {
3496 if (layer->setSize(s.w, s.h)) {
3497 flags |= eTraversalNeeded;
3498 }
3499 }
3500 if (what & layer_state_t::eAlphaChanged) {
3501 if (layer->setAlpha(s.alpha))
3502 flags |= eTraversalNeeded;
3503 }
3504 if (what & layer_state_t::eColorChanged) {
3505 if (layer->setColor(s.color))
3506 flags |= eTraversalNeeded;
3507 }
3508 if (what & layer_state_t::eMatrixChanged) {
3509 if (layer->setMatrix(s.matrix))
3510 flags |= eTraversalNeeded;
3511 }
3512 if (what & layer_state_t::eTransparentRegionChanged) {
3513 if (layer->setTransparentRegionHint(s.transparentRegion))
3514 flags |= eTraversalNeeded;
3515 }
3516 if (what & layer_state_t::eFlagsChanged) {
3517 if (layer->setFlags(s.flags, s.mask))
3518 flags |= eTraversalNeeded;
3519 }
3520 if (what & layer_state_t::eCropChanged) {
3521 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3522 flags |= eTraversalNeeded;
3523 }
3524 if (what & layer_state_t::eFinalCropChanged) {
3525 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3526 flags |= eTraversalNeeded;
3527 }
3528 if (what & layer_state_t::eLayerStackChanged) {
3529 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3530 // We only allow setting layer stacks for top level layers,
3531 // everything else inherits layer stack from its parent.
3532 if (layer->hasParent()) {
3533 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3534 layer->getName().string());
3535 } else if (idx < 0) {
3536 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3537 "that also does not appear in the top level layer list. Something"
3538 " has gone wrong.", layer->getName().string());
3539 } else if (layer->setLayerStack(s.layerStack)) {
3540 mCurrentState.layersSortedByZ.removeAt(idx);
3541 mCurrentState.layersSortedByZ.add(layer);
3542 // we need traversal (state changed)
3543 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003544 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003545 }
3546 }
3547 if (what & layer_state_t::eDeferTransaction) {
3548 if (s.barrierHandle != nullptr) {
3549 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3550 } else if (s.barrierGbp != nullptr) {
3551 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3552 if (authenticateSurfaceTextureLocked(gbp)) {
3553 const auto& otherLayer =
3554 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3555 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3556 } else {
3557 ALOGE("Attempt to defer transaction to to an"
3558 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003559 }
3560 }
chaviw8b3871a2017-11-01 17:41:01 -07003561 // We don't trigger a traversal here because if no other state is
3562 // changed, we don't want this to cause any more work
3563 }
3564 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003565 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003566 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003567 if (!hadParent) {
3568 mCurrentState.layersSortedByZ.remove(layer);
3569 }
chaviw8b3871a2017-11-01 17:41:01 -07003570 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003571 }
chaviw8b3871a2017-11-01 17:41:01 -07003572 }
3573 if (what & layer_state_t::eReparentChildren) {
3574 if (layer->reparentChildren(s.reparentHandle)) {
3575 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003576 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003577 }
chaviw8b3871a2017-11-01 17:41:01 -07003578 if (what & layer_state_t::eDetachChildren) {
3579 layer->detachChildren();
3580 }
3581 if (what & layer_state_t::eOverrideScalingModeChanged) {
3582 layer->setOverrideScalingMode(s.overrideScalingMode);
3583 // We don't trigger a traversal here because if no other state is
3584 // changed, we don't want this to cause any more work
3585 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003586 return flags;
3587}
3588
chaviwca27f252018-02-06 16:46:39 -08003589void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3590 const layer_state_t& state = composerState.state;
3591 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3592
3593 sp<Layer> layer(client->getLayerUser(state.surface));
3594 if (layer == nullptr) {
3595 return;
3596 }
3597
3598 if (layer->isPendingRemoval()) {
3599 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3600 return;
3601 }
3602
3603 if (state.what & layer_state_t::eDestroySurface) {
3604 removeLayerLocked(mStateLock, layer);
3605 }
3606}
3607
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003608status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003609 const String8& name,
3610 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003611 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliuccd34842018-03-14 12:26:23 -07003612 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003613 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003614{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003615 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003616 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003617 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003618 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003619 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003620
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003621 status_t result = NO_ERROR;
3622
3623 sp<Layer> layer;
3624
Cody Northropbc755282017-03-31 12:00:08 -06003625 String8 uniqueName = getUniqueLayerName(name);
3626
Mathias Agopian3165cc22012-08-08 19:42:09 -07003627 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3628 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003629 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003630 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003631 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003632
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003633 break;
chaviw13fdc492017-06-27 12:40:18 -07003634 case ISurfaceComposerClient::eFXSurfaceColor:
3635 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003636 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003637 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003638 break;
3639 default:
3640 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003641 break;
3642 }
3643
Dan Stoza7d89d062015-04-30 13:29:25 -07003644 if (result != NO_ERROR) {
3645 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003646 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003647
Chia-I Wuab0c3192017-08-01 11:29:00 -07003648 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3649 // TODO b/64227542
3650 if (windowType == 441731) {
3651 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3652 layer->setPrimaryDisplayOnly();
3653 }
3654
Albert Chaulk479c60c2017-01-27 14:21:34 -05003655 layer->setInfo(windowType, ownerUid);
3656
Robert Carr1f0a16a2016-10-24 16:27:39 -07003657 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003658 if (result != NO_ERROR) {
3659 return result;
3660 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003661 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003662
3663 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003664 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003665}
3666
Cody Northropbc755282017-03-31 12:00:08 -06003667String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3668{
3669 bool matchFound = true;
3670 uint32_t dupeCounter = 0;
3671
3672 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3673 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3674
Dan Stoza9fdb7e02018-06-21 12:10:12 -07003675 // Grab the state lock since we're accessing mCurrentState
3676 Mutex::Autolock lock(mStateLock);
3677
Cody Northropbc755282017-03-31 12:00:08 -06003678 // Loop over layers until we're sure there is no matching name
3679 while (matchFound) {
3680 matchFound = false;
Dan Stoza9fdb7e02018-06-21 12:10:12 -07003681 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003682 if (layer->getName() == uniqueName) {
3683 matchFound = true;
3684 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3685 }
3686 });
3687 }
3688
3689 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3690
3691 return uniqueName;
3692}
3693
David Sodman0c69cad2017-08-21 12:12:51 -07003694status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003695 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3696 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003697{
3698 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003699 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003700 case PIXEL_FORMAT_TRANSPARENT:
3701 case PIXEL_FORMAT_TRANSLUCENT:
3702 format = PIXEL_FORMAT_RGBA_8888;
3703 break;
3704 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003705 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003706 break;
3707 }
3708
David Sodman0c69cad2017-08-21 12:12:51 -07003709 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3710 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003711 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003712 *handle = layer->getHandle();
3713 *gbp = layer->getProducer();
3714 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003715 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003716
David Sodman0c69cad2017-08-21 12:12:51 -07003717 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003718 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003719}
3720
chaviw13fdc492017-06-27 12:40:18 -07003721status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003722 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003723 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003724{
chaviw13fdc492017-06-27 12:40:18 -07003725 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003726 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003727 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003728}
3729
Mathias Agopianac9fa422013-02-11 16:40:36 -08003730status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003731{
Robert Carr9524cb32017-02-13 11:32:32 -08003732 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003733 status_t err = NO_ERROR;
3734 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003735 if (l != nullptr) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003736 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003737 err = removeLayer(l);
3738 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3739 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003740 }
3741 return err;
3742}
3743
Mathias Agopian13127d82013-03-05 17:47:11 -08003744status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003745{
Mathias Agopian67106042013-03-14 19:18:13 -07003746 // called by ~LayerCleaner() when all references to the IBinder (handle)
3747 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003748 sp<Layer> l = layer.promote();
3749 if (l == nullptr) {
3750 // The layer has already been removed, carry on
3751 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003752 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003753 // If we have a parent, then we can continue to live as long as it does.
3754 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003755}
3756
Mathias Agopianb60314a2012-04-10 22:09:54 -07003757// ---------------------------------------------------------------------------
3758
Andy McFadden13a082e2012-08-24 10:16:42 -07003759void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003760 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003761 Vector<ComposerState> state;
3762 Vector<DisplayState> displays;
3763 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003764 d.what = DisplayState::eDisplayProjectionChanged |
3765 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003766 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003767 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003768 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003769 d.frame.makeInvalid();
3770 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003771 d.width = 0;
3772 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003773 displays.add(d);
3774 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003775 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3776 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003777
David Sodman105b7dc2017-11-04 20:28:14 -07003778 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003779 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003780 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003781
Brian Andersond0010582017-03-07 13:20:31 -08003782 // Use phase of 0 since phase is not known.
3783 // Use latency of 0, which will snap to the ideal latency.
3784 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003785}
3786
3787void SurfaceFlinger::initializeDisplays() {
3788 class MessageScreenInitialized : public MessageBase {
3789 SurfaceFlinger* flinger;
3790 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003791 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003792 virtual bool handler() {
3793 flinger->onInitializeDisplays();
3794 return true;
3795 }
3796 };
3797 sp<MessageBase> msg = new MessageScreenInitialized(this);
3798 postMessageAsync(msg); // we may be called from main thread, use async message
3799}
3800
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003801void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003802 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003803 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3804 this);
3805 int32_t type = hw->getDisplayType();
3806 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003807
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003808 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003809 return;
3810 }
3811
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003812 hw->setPowerMode(mode);
3813 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3814 ALOGW("Trying to set power mode for virtual display");
3815 return;
3816 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003817
Lloyd Pique4d234852018-01-22 17:21:36 -08003818 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003819 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003820 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3821 if (idx < 0) {
3822 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3823 return;
3824 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003825 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003826 }
3827
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003828 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003829 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003830 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003831 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3832 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003833 // FIXME: eventthread only knows about the main display right now
3834 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003835 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003836 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003837
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003838 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003839 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003840 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003841
3842 struct sched_param param = {0};
3843 param.sched_priority = 1;
3844 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3845 ALOGW("Couldn't set SCHED_FIFO on display on");
3846 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003847 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003848 // Turn off the display
3849 struct sched_param param = {0};
3850 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3851 ALOGW("Couldn't set SCHED_OTHER on display off");
3852 }
3853
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003854 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3855 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003856 disableHardwareVsync(true); // also cancels any in-progress resync
3857
Mathias Agopiancde87a32012-09-13 14:09:01 -07003858 // FIXME: eventthread only knows about the main display right now
3859 mEventThread->onScreenReleased();
3860 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003861
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003862 getHwComposer().setPowerMode(type, mode);
3863 mVisibleRegionsDirty = true;
3864 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003865 } else if (mode == HWC_POWER_MODE_DOZE ||
3866 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003867 // Update display while dozing
3868 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003869 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3870 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003871 // FIXME: eventthread only knows about the main display right now
3872 mEventThread->onScreenAcquired();
3873 resyncToHardwareVsync(true);
3874 }
3875 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3876 // Leave display going to doze
3877 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3878 disableHardwareVsync(true); // also cancels any in-progress resync
3879 // FIXME: eventthread only knows about the main display right now
3880 mEventThread->onScreenReleased();
3881 }
3882 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003883 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003884 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003885 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003886 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003887 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003888}
3889
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003890void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3891 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003892 SurfaceFlinger& mFlinger;
3893 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003894 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003895 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003896 MessageSetPowerMode(SurfaceFlinger& flinger,
3897 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3898 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003899 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003900 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003901 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003902 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003903 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003904 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003905 ALOGW("Attempt to set power mode = %d for virtual display",
3906 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003907 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003908 mFlinger.setPowerModeInternal(
3909 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003910 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003911 return true;
3912 }
3913 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003914 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003915 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003916}
3917
3918// ---------------------------------------------------------------------------
3919
Lloyd Pique755e3192018-01-31 16:46:15 -08003920status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3921 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003922 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003923
Mathias Agopianbd115332013-04-18 16:41:04 -07003924 IPCThreadState* ipc = IPCThreadState::self();
3925 const int pid = ipc->getCallingPid();
3926 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003927
Mathias Agopianbd115332013-04-18 16:41:04 -07003928 if ((uid != AID_SHELL) &&
3929 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003930 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003931 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003932 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003933 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003934 // (this would indicate SF is stuck, but we want to be able to
3935 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003936 status_t err = mStateLock.timedLock(s2ns(1));
3937 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003938 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003939 result.appendFormat(
3940 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3941 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003942 }
3943
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003944 bool dumpAll = true;
3945 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003946 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003947
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003948 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003949 if ((index < numArgs) &&
3950 (args[index] == String16("--list"))) {
3951 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003952 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003953 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003954 }
3955
3956 if ((index < numArgs) &&
3957 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003958 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003959 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003960 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003961 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003962
3963 if ((index < numArgs) &&
3964 (args[index] == String16("--latency-clear"))) {
3965 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003966 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003967 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003968 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003969
3970 if ((index < numArgs) &&
3971 (args[index] == String16("--dispsync"))) {
3972 index++;
3973 mPrimaryDispSync.dump(result);
3974 dumpAll = false;
3975 }
Dan Stozab90cf072015-03-05 11:05:59 -08003976
3977 if ((index < numArgs) &&
3978 (args[index] == String16("--static-screen"))) {
3979 index++;
3980 dumpStaticScreenStats(result);
3981 dumpAll = false;
3982 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003983
3984 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003985 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003986 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003987 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003988 dumpAll = false;
3989 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003990
3991 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3992 index++;
3993 dumpWideColorInfo(result);
3994 dumpAll = false;
3995 }
Yiwei Zhang068e31b2018-02-21 13:02:45 -08003996
3997 if ((index < numArgs) &&
3998 (args[index] == String16("--enable-layer-stats"))) {
3999 index++;
4000 mLayerStats.enable();
4001 dumpAll = false;
4002 }
4003
4004 if ((index < numArgs) &&
4005 (args[index] == String16("--disable-layer-stats"))) {
4006 index++;
4007 mLayerStats.disable();
4008 dumpAll = false;
4009 }
4010
4011 if ((index < numArgs) &&
4012 (args[index] == String16("--clear-layer-stats"))) {
4013 index++;
4014 mLayerStats.clear();
4015 dumpAll = false;
4016 }
4017
4018 if ((index < numArgs) &&
4019 (args[index] == String16("--dump-layer-stats"))) {
4020 index++;
4021 mLayerStats.dump(result);
4022 dumpAll = false;
4023 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -07004024
4025 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4026 index++;
4027 mTimeStats.parseArgs(asProto, args, index, result);
4028 dumpAll = false;
4029 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004030 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004031
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004032 if (dumpAll) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -07004033 if (asProto) {
4034 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4035 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4036 } else {
4037 dumpAllLocked(args, index, result);
4038 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004039 }
4040
Mathias Agopian9795c422009-08-26 16:36:26 -07004041 if (locked) {
4042 mStateLock.unlock();
4043 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004044 }
4045 write(fd, result.string(), result.size());
4046 return NO_ERROR;
4047}
4048
Dan Stozac7014012014-02-14 15:03:43 -08004049void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4050 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004051{
Robert Carr2047fae2016-11-28 14:09:09 -08004052 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004053 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004054 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004055}
4056
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004057void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004058 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004059{
4060 String8 name;
4061 if (index < args.size()) {
4062 name = String8(args[index]);
4063 index++;
4064 }
4065
David Sodman105b7dc2017-11-04 20:28:14 -07004066 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004067 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08004068 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004069
4070 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004071 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004072 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004073 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004074 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004075 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004076 }
Robert Carr2047fae2016-11-28 14:09:09 -08004077 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004078 }
4079}
4080
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004081void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004082 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004083{
4084 String8 name;
4085 if (index < args.size()) {
4086 name = String8(args[index]);
4087 index++;
4088 }
4089
Robert Carr2047fae2016-11-28 14:09:09 -08004090 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004091 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004092 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004093 }
Robert Carr2047fae2016-11-28 14:09:09 -08004094 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004095
Svetoslavd85084b2014-03-20 10:28:31 -07004096 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004097}
4098
Jamie Gennis6547ff42013-07-16 20:12:42 -07004099// This should only be called from the main thread. Otherwise it would need
4100// the lock and should use mCurrentState rather than mDrawingState.
4101void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004102 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004103 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004104 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004105
4106 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4107}
4108
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004109void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004110{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004111 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004112
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004113 if (isLayerTripleBufferingDisabled())
4114 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004115
4116 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004117 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004118 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004119 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004120 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4121 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004122 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004123}
4124
Dan Stozab90cf072015-03-05 11:05:59 -08004125void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4126{
4127 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004128 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4129 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004130 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004131 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004132 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4133 b + 1, bucketTimeSec, percent);
4134 }
David Sodman4a36e932017-11-07 14:29:47 -08004135 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004136 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004137 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004138 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004139 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004140}
4141
Dan Stozae77c7662016-05-13 11:37:28 -07004142void SurfaceFlinger::recordBufferingStats(const char* layerName,
4143 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004144 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4145 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004146 for (const auto& segment : history) {
4147 if (!segment.usedThirdBuffer) {
4148 stats.twoBufferTime += segment.totalTime;
4149 }
4150 if (segment.occupancyAverage < 1.0f) {
4151 stats.doubleBufferedTime += segment.totalTime;
4152 } else if (segment.occupancyAverage < 2.0f) {
4153 stats.tripleBufferedTime += segment.totalTime;
4154 }
4155 ++stats.numSegments;
4156 stats.totalTime += segment.totalTime;
4157 }
4158}
4159
Brian Andersond6927fb2016-07-23 23:37:30 -07004160void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4161 result.appendFormat("Layer frame timestamps:\n");
4162
4163 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4164 const size_t count = currentLayers.size();
4165 for (size_t i=0 ; i<count ; i++) {
4166 currentLayers[i]->dumpFrameEvents(result);
4167 }
4168}
4169
Dan Stozae77c7662016-05-13 11:37:28 -07004170void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4171 result.append("Buffering stats:\n");
4172 result.append(" [Layer name] <Active time> <Two buffer> "
4173 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004174 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004175 typedef std::tuple<std::string, float, float, float> BufferTuple;
4176 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004177 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004178 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004179 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004180 if (stats.numSegments == 0) {
4181 continue;
4182 }
4183 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4184 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4185 stats.totalTime;
4186 float doubleBufferRatio = static_cast<float>(
4187 stats.doubleBufferedTime) / stats.totalTime;
4188 float tripleBufferRatio = static_cast<float>(
4189 stats.tripleBufferedTime) / stats.totalTime;
4190 sorted.insert({activeTime, {name, twoBufferRatio,
4191 doubleBufferRatio, tripleBufferRatio}});
4192 }
4193 for (const auto& sortedPair : sorted) {
4194 float activeTime = sortedPair.first;
4195 const BufferTuple& values = sortedPair.second;
4196 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4197 std::get<0>(values).c_str(), activeTime,
4198 std::get<1>(values), std::get<2>(values),
4199 std::get<3>(values));
4200 }
4201 result.append("\n");
4202}
4203
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004204void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4205 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004206 result.appendFormat("DisplayColorSetting: %d\n", mDisplayColorSetting);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004207
4208 // TODO: print out if wide-color mode is active or not
4209
4210 for (size_t d = 0; d < mDisplays.size(); d++) {
4211 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4212 int32_t hwcId = displayDevice->getHwcDisplayId();
4213 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4214 continue;
4215 }
4216
4217 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004218 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004219 for (auto&& mode : modes) {
4220 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4221 }
4222
Peiyong Lina52f0292018-03-14 17:26:31 -07004223 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004224 result.appendFormat(" Current color mode: %s (%d)\n",
4225 decodeColorMode(currentMode).c_str(), currentMode);
4226 }
4227 result.append("\n");
4228}
4229
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004230LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004231 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004232 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4233 const State& state = useDrawing ? mDrawingState : mCurrentState;
4234 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004235 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004236 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004237 });
4238
4239 return layersProto;
4240}
4241
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004242LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4243 LayersProto layersProto;
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004244 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004245
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004246 SizeProto* resolution = layersProto.mutable_resolution();
4247 resolution->set_w(displayDevice->getWidth());
4248 resolution->set_h(displayDevice->getHeight());
4249
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004250 layersProto.set_color_mode(decodeColorMode(displayDevice->getActiveColorMode()));
4251 layersProto.set_color_transform(decodeColorTransform(displayDevice->getColorTransform()));
4252 layersProto.set_global_transform(
4253 static_cast<int32_t>(displayDevice->getOrientationTransform()));
4254
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004255 mDrawingState.traverseInZOrder([&](Layer* layer) {
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004256 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004257 LayerProto* layerProto = layersProto.add_layers();
4258 layer->writeToProto(layerProto, hwcId);
4259 }
4260 });
4261
4262 return layersProto;
4263}
4264
Mathias Agopian74d211a2013-04-22 16:55:35 +02004265void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4266 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004267{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004268 bool colorize = false;
4269 if (index < args.size()
4270 && (args[index] == String16("--color"))) {
4271 colorize = true;
4272 index++;
4273 }
4274
4275 Colorizer colorizer(colorize);
4276
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004277 // figure out if we're stuck somewhere
4278 const nsecs_t now = systemTime();
4279 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4280 const nsecs_t inTransaction(mDebugInTransaction);
4281 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4282 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4283
4284 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004285 * Dump library configuration.
4286 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004287
4288 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004289 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004290 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004291 appendSfConfigString(result);
4292 appendUiConfigString(result);
4293 appendGuiConfigString(result);
4294 result.append("\n");
4295
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004296 result.append("\nWide-Color information:\n");
4297 dumpWideColorInfo(result);
4298
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004299 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004300 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004301 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004302 result.append(SyncFeatures::getInstance().toString());
4303 result.append("\n");
4304
David Sodman105b7dc2017-11-04 20:28:14 -07004305 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004306
Andy McFadden41d67d72014-04-25 16:58:34 -07004307 colorizer.bold(result);
4308 result.append("DispSync configuration: ");
4309 colorizer.reset(result);
Dan Stoza2713c302018-03-28 17:07:36 -07004310 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, early sf phase %" PRId64
4311 " ns, present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4312 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, mVsyncModulator.getEarlyPhaseOffset(),
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004313 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004314 result.append("\n");
4315
Dan Stozab90cf072015-03-05 11:05:59 -08004316 // Dump static screen stats
4317 result.append("\n");
4318 dumpStaticScreenStats(result);
4319 result.append("\n");
4320
Dan Stozae77c7662016-05-13 11:37:28 -07004321 dumpBufferingStats(result);
4322
Andy McFadden4803b742012-09-24 19:07:20 -07004323 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004324 * Dump the visible layer list
4325 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004326 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004327 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004328 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4329 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004330 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004331
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004332 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004333 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7794ec12018-03-14 13:28:39 -07004334 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004335 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004336
4337 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004338 * Dump Display state
4339 */
4340
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004341 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004342 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004343 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004344 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4345 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004346 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004347 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004348 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004349
4350 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004351 * Dump SurfaceFlinger global state
4352 */
4353
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004354 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004355 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004356 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004357
Mathias Agopian888c8222012-08-04 21:10:38 -07004358 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004359 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004360
David Sodmanbc815282017-11-05 18:57:52 -08004361 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004362
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004363 if (hw) {
4364 hw->undefinedRegion.dump(result, "undefinedRegion");
4365 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4366 hw->getOrientation(), hw->isDisplayOn());
4367 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004368 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004369 " last eglSwapBuffers() time: %f us\n"
4370 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004371 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004372 " refresh-rate : %f fps\n"
4373 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004374 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004375 " gpu_to_cpu_unsupported : %d\n"
4376 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004377 mLastSwapBufferTime/1000.0,
4378 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004379 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004380 1e9 / activeConfig->getVsyncPeriod(),
4381 activeConfig->getDpiX(),
4382 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004383 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004384
Mathias Agopian74d211a2013-04-22 16:55:35 +02004385 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004386 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004387
Mathias Agopian74d211a2013-04-22 16:55:35 +02004388 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004389 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004390
4391 /*
4392 * VSYNC state
4393 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004394 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004395 result.append("\n");
4396
4397 /*
4398 * HWC layer minidump
4399 */
4400 for (size_t d = 0; d < mDisplays.size(); d++) {
4401 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4402 int32_t hwcId = displayDevice->getHwcDisplayId();
4403 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4404 continue;
4405 }
4406
4407 result.appendFormat("Display %d HWC layers:\n", hwcId);
4408 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004409 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004410 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004411 });
Dan Stozae22aec72016-08-01 13:20:59 -07004412 result.append("\n");
4413 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004414
4415 /*
4416 * Dump HWComposer state
4417 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004418 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004419 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004420 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004421 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004422 result.appendFormat(" h/w composer %s\n",
4423 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004424 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004425
4426 /*
4427 * Dump gralloc state
4428 */
4429 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4430 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004431
4432 /*
4433 * Dump VrFlinger state if in use.
4434 */
4435 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4436 result.append("VrFlinger state:\n");
4437 result.append(mVrFlinger->Dump().c_str());
4438 result.append("\n");
4439 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004440}
4441
Mathias Agopian13127d82013-03-05 17:47:11 -08004442const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004443SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004444 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004445 wp<IBinder> dpy;
4446 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4447 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4448 dpy = mDisplays.keyAt(i);
4449 break;
4450 }
4451 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004452 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004453 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4454 // Just use the primary display so we have something to return
4455 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4456 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004457 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004458}
4459
Keun young Park63f165f2012-08-31 10:53:36 -07004460bool SurfaceFlinger::startDdmConnection()
4461{
4462 void* libddmconnection_dso =
4463 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4464 if (!libddmconnection_dso) {
4465 return false;
4466 }
4467 void (*DdmConnection_start)(const char* name);
4468 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004469 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004470 if (!DdmConnection_start) {
4471 dlclose(libddmconnection_dso);
4472 return false;
4473 }
4474 (*DdmConnection_start)(getServiceName());
4475 return true;
4476}
4477
Chia-I Wu28f320b2018-05-03 11:02:56 -07004478void SurfaceFlinger::updateColorMatrixLocked() {
4479 mat4 colorMatrix;
4480 if (mGlobalSaturationFactor != 1.0f) {
4481 // Rec.709 luma coefficients
4482 float3 luminance{0.213f, 0.715f, 0.072f};
4483 luminance *= 1.0f - mGlobalSaturationFactor;
4484 mat4 saturationMatrix = mat4(
4485 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4486 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4487 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4488 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4489 );
4490 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4491 } else {
4492 colorMatrix = mClientColorMatrix * mDaltonizer();
4493 }
4494
4495 if (mCurrentState.colorMatrix != colorMatrix) {
4496 mCurrentState.colorMatrix = colorMatrix;
4497 mCurrentState.colorMatrixChanged = true;
4498 setTransactionFlags(eTransactionNeeded);
4499 }
4500}
4501
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004502status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004503 switch (code) {
4504 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004505 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004506 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004507 case CLEAR_ANIMATION_FRAME_STATS:
4508 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004509 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004510 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004511 case ENABLE_VSYNC_INJECTIONS:
4512 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004513 {
4514 // codes that require permission check
4515 IPCThreadState* ipc = IPCThreadState::self();
4516 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004517 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004518 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004519 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004520 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004521 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004522 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004523 break;
4524 }
Robert Carr1db73f62016-12-21 12:58:51 -08004525 /*
4526 * Calling setTransactionState is safe, because you need to have been
4527 * granted a reference to Client* and Handle* to do anything with it.
4528 *
4529 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4530 */
4531 case SET_TRANSACTION_STATE:
4532 case CREATE_SCOPED_CONNECTION:
4533 {
4534 return OK;
4535 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004536 case CAPTURE_SCREEN:
4537 {
4538 // codes that require permission check
4539 IPCThreadState* ipc = IPCThreadState::self();
4540 const int pid = ipc->getCallingPid();
4541 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004542 if ((uid != AID_GRAPHICS) &&
4543 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004544 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004545 return PERMISSION_DENIED;
4546 }
4547 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004548 }
chaviwa76b2712017-09-20 12:02:26 -07004549 case CAPTURE_LAYERS: {
4550 IPCThreadState* ipc = IPCThreadState::self();
4551 const int pid = ipc->getCallingPid();
4552 const int uid = ipc->getCallingUid();
4553 if ((uid != AID_GRAPHICS) &&
4554 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4555 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4556 return PERMISSION_DENIED;
4557 }
4558 break;
4559 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004560 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004561 return OK;
4562}
4563
4564status_t SurfaceFlinger::onTransact(
4565 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4566{
4567 status_t credentialCheck = CheckTransactCodeCredentials(code);
4568 if (credentialCheck != OK) {
4569 return credentialCheck;
4570 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004571
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004572 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4573 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004574 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004575 IPCThreadState* ipc = IPCThreadState::self();
4576 const int uid = ipc->getCallingUid();
4577 if (CC_UNLIKELY(uid != AID_SYSTEM
4578 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004579 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004580 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004581 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004582 return PERMISSION_DENIED;
4583 }
4584 int n;
4585 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004586 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004587 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004588 return NO_ERROR;
4589 case 1002: // SHOW_UPDATES
4590 n = data.readInt32();
4591 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004592 invalidateHwcGeometry();
4593 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004594 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004595 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004596 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004597 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004598 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004599 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004600 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004601 setTransactionFlags(
4602 eTransactionNeeded|
4603 eDisplayTransactionNeeded|
4604 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004605 return NO_ERROR;
4606 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004607 case 1006:{ // send empty update
4608 signalRefresh();
4609 return NO_ERROR;
4610 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004611 case 1008: // toggle use of hw composer
4612 n = data.readInt32();
4613 mDebugDisableHWC = n ? 1 : 0;
4614 invalidateHwcGeometry();
4615 repaintEverything();
4616 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004617 case 1009: // toggle use of transform hint
4618 n = data.readInt32();
4619 mDebugDisableTransformHint = n ? 1 : 0;
4620 invalidateHwcGeometry();
4621 repaintEverything();
4622 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004623 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004624 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004625 reply->writeInt32(0);
4626 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004627 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004628 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004629 return NO_ERROR;
4630 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004631 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004632 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004633 return NO_ERROR;
4634 }
4635 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004636 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004637 // daltonize
4638 n = data.readInt32();
4639 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004640 case 1:
4641 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4642 break;
4643 case 2:
4644 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4645 break;
4646 case 3:
4647 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4648 break;
4649 default:
4650 mDaltonizer.setType(ColorBlindnessType::None);
4651 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004652 }
4653 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004654 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004655 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004656 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004657 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004658
4659 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004660 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004661 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004662 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004663 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004664 // apply a color matrix
4665 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004666 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004667 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004668 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004669 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004670 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004671 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004672 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004673 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004674 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004675 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004676
4677 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4678 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004679 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004680 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4681 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4682 }
4683
Chia-I Wu28f320b2018-05-03 11:02:56 -07004684 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004685 return NO_ERROR;
4686 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004687 // This is an experimental interface
4688 // Needs to be shifted to proper binder interface when we productize
4689 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004690 n = data.readInt32();
4691 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004692 return NO_ERROR;
4693 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004694 case 1017: {
4695 n = data.readInt32();
4696 mForceFullDamage = static_cast<bool>(n);
4697 return NO_ERROR;
4698 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004699 case 1018: { // Modify Choreographer's phase offset
4700 n = data.readInt32();
4701 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4702 return NO_ERROR;
4703 }
4704 case 1019: { // Modify SurfaceFlinger's phase offset
4705 n = data.readInt32();
4706 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4707 return NO_ERROR;
4708 }
Irvel468051e2016-06-13 16:44:44 -07004709 case 1020: { // Layer updates interceptor
4710 n = data.readInt32();
4711 if (n) {
4712 ALOGV("Interceptor enabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004713 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004714 }
4715 else{
4716 ALOGV("Interceptor disabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004717 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004718 }
4719 return NO_ERROR;
4720 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004721 case 1021: { // Disable HWC virtual displays
4722 n = data.readInt32();
4723 mUseHwcVirtualDisplays = !n;
4724 return NO_ERROR;
4725 }
Romain Guy0147a172017-06-01 13:53:56 -07004726 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004727 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004728 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004729
Chia-I Wu28f320b2018-05-03 11:02:56 -07004730 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004731 return NO_ERROR;
4732 }
Romain Guy54f154a2017-10-24 21:40:32 +01004733 case 1023: { // Set native mode
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004734 int32_t value = data.readInt32();
4735 if (value > 2) {
4736 return BAD_VALUE;
4737 }
4738 if (value == 2 && !mBuiltinDisplaySupportsEnhance) {
4739 return BAD_VALUE;
4740 }
Romain Guy54f154a2017-10-24 21:40:32 +01004741
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004742 mDisplayColorSetting = toDisplayColorSetting(value);
Romain Guy54f154a2017-10-24 21:40:32 +01004743 invalidateHwcGeometry();
4744 repaintEverything();
4745 return NO_ERROR;
4746 }
4747 case 1024: { // Is wide color gamut rendering/color management supported?
4748 reply->writeBool(hasWideColorDisplay);
4749 return NO_ERROR;
4750 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004751 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004752 n = data.readInt32();
4753 if (n) {
4754 ALOGV("LayerTracing enabled");
4755 mTracing.enable();
4756 doTracing("tracing.enable");
4757 reply->writeInt32(NO_ERROR);
4758 } else {
4759 ALOGV("LayerTracing disabled");
4760 status_t err = mTracing.disable();
4761 reply->writeInt32(err);
4762 }
4763 return NO_ERROR;
4764 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004765 case 1026: { // Get layer tracing status
4766 reply->writeBool(mTracing.isEnabled());
4767 return NO_ERROR;
4768 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004769 // Is a DisplayColorSetting supported?
4770 case 1027: {
4771 int32_t value = data.readInt32();
4772 switch (value) {
4773 case 0:
4774 reply->writeBool(hasWideColorDisplay);
4775 return NO_ERROR;
4776 case 1:
4777 reply->writeBool(true);
4778 return NO_ERROR;
4779 case 2:
4780 reply->writeBool(mBuiltinDisplaySupportsEnhance);
4781 return NO_ERROR;
4782 default:
4783 return BAD_VALUE;
4784 }
4785 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004786 }
4787 }
4788 return err;
4789}
4790
Steven Thomas6d8110b2017-08-31 18:24:21 -07004791void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004792 android_atomic_or(1, &mRepaintEverything);
4793 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004794}
4795
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004796// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4797class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004798public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004799 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4800 ~WindowDisconnector() {
4801 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004802 }
4803
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004804private:
4805 ANativeWindow* mWindow;
4806 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004807};
4808
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004809status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4810 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4811 int32_t minLayerZ, int32_t maxLayerZ,
4812 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004813 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004814 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004815
chaviwa76b2712017-09-20 12:02:26 -07004816 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4817
4818 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004819 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4820
chaviwa76b2712017-09-20 12:02:26 -07004821 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4822
4823 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4824 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004825 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004826}
4827
4828status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004829 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004830 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004831 ATRACE_CALL();
4832
4833 class LayerRenderArea : public RenderArea {
4834 public:
Robert Carr578038f2018-03-09 12:25:24 -08004835 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4836 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004837 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004838 mLayer(layer),
4839 mCrop(crop),
4840 mFlinger(flinger),
4841 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004842 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004843 Rect getBounds() const override {
4844 const Layer::State& layerState(mLayer->getDrawingState());
4845 return Rect(layerState.active.w, layerState.active.h);
4846 }
4847 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4848 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4849 bool isSecure() const override { return false; }
4850 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004851 Rect getSourceCrop() const override {
4852 if (mCrop.isEmpty()) {
4853 return getBounds();
4854 } else {
4855 return mCrop;
4856 }
4857 }
4858 bool getWideColorSupport() const override { return false; }
4859 Dataspace getDataSpace() const override { return Dataspace::UNKNOWN; }
Peiyong Linfb069302018-04-25 14:34:31 -07004860 float getDisplayMaxLuminance() const override {
4861 return DisplayDevice::sDefaultMaxLumiance;
4862 }
Robert Carr578038f2018-03-09 12:25:24 -08004863
4864 class ReparentForDrawing {
4865 public:
4866 const sp<Layer>& oldParent;
4867 const sp<Layer>& newParent;
4868
4869 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4870 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004871 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004872 }
Robert Carr15eae092018-03-23 13:43:53 -07004873 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004874 };
4875
4876 void render(std::function<void()> drawLayers) override {
4877 if (!mChildrenOnly) {
4878 mTransform = mLayer->getTransform().inverse();
4879 drawLayers();
4880 } else {
4881 Rect bounds = getBounds();
4882 screenshotParentLayer =
4883 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4884 bounds.getWidth(), bounds.getHeight(), 0);
4885
4886 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4887 drawLayers();
4888 }
4889 }
chaviwa76b2712017-09-20 12:02:26 -07004890
chaviwa76b2712017-09-20 12:02:26 -07004891 private:
chaviw7206d492017-11-10 16:16:12 -08004892 const sp<Layer> mLayer;
4893 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004894
4895 // In the "childrenOnly" case we reparent the children to a screenshot
4896 // layer which has no properties set and which does not draw.
4897 sp<ContainerLayer> screenshotParentLayer;
4898 Transform mTransform;
4899
4900 SurfaceFlinger* mFlinger;
4901 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004902 };
4903
4904 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4905 auto parent = layerHandle->owner.promote();
4906
chaviw7206d492017-11-10 16:16:12 -08004907 if (parent == nullptr || parent->isPendingRemoval()) {
4908 ALOGE("captureLayers called with a removed parent");
4909 return NAME_NOT_FOUND;
4910 }
4911
Robert Carr578038f2018-03-09 12:25:24 -08004912 const int uid = IPCThreadState::self()->getCallingUid();
4913 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4914 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4915 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4916 return PERMISSION_DENIED;
4917 }
4918
chaviw7206d492017-11-10 16:16:12 -08004919 Rect crop(sourceCrop);
4920 if (sourceCrop.width() <= 0) {
4921 crop.left = 0;
4922 crop.right = parent->getCurrentState().active.w;
4923 }
4924
4925 if (sourceCrop.height() <= 0) {
4926 crop.top = 0;
4927 crop.bottom = parent->getCurrentState().active.h;
4928 }
4929
4930 int32_t reqWidth = crop.width() * frameScale;
4931 int32_t reqHeight = crop.height() * frameScale;
4932
Robert Carr578038f2018-03-09 12:25:24 -08004933 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004934
Robert Carr578038f2018-03-09 12:25:24 -08004935 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004936 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4937 if (!layer->isVisible()) {
4938 return;
Robert Carr578038f2018-03-09 12:25:24 -08004939 } else if (childrenOnly && layer == parent.get()) {
4940 return;
chaviwa76b2712017-09-20 12:02:26 -07004941 }
4942 visitor(layer);
4943 });
4944 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004945 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004946}
4947
4948status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4949 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004950 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004951 bool useIdentityTransform) {
4952 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004953
chaviwa76b2712017-09-20 12:02:26 -07004954 renderArea.updateDimensions();
4955
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004956 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4957 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4958 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4959 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004960
4961 // This mutex protects syncFd and captureResult for communication of the return values from the
4962 // main thread back to this Binder thread
4963 std::mutex captureMutex;
4964 std::condition_variable captureCondition;
4965 std::unique_lock<std::mutex> captureLock(captureMutex);
4966 int syncFd = -1;
4967 std::optional<status_t> captureResult;
4968
Robert Carr03480e22018-01-04 16:02:06 -08004969 const int uid = IPCThreadState::self()->getCallingUid();
4970 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4971
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004972 sp<LambdaMessage> message = new LambdaMessage([&]() {
4973 // If there is a refresh pending, bug out early and tell the binder thread to try again
4974 // after the refresh.
4975 if (mRefreshPending) {
4976 ATRACE_NAME("Skipping screenshot for now");
4977 std::unique_lock<std::mutex> captureLock(captureMutex);
4978 captureResult = std::make_optional<status_t>(EAGAIN);
4979 captureCondition.notify_one();
4980 return;
4981 }
4982
4983 status_t result = NO_ERROR;
4984 int fd = -1;
4985 {
4986 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004987 renderArea.render([&]() {
4988 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4989 useIdentityTransform, forSystem, &fd);
4990 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004991 }
4992
4993 {
4994 std::unique_lock<std::mutex> captureLock(captureMutex);
4995 syncFd = fd;
4996 captureResult = std::make_optional<status_t>(result);
4997 captureCondition.notify_one();
4998 }
4999 });
5000
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005001 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005002 if (result == NO_ERROR) {
5003 captureCondition.wait(captureLock, [&]() { return captureResult; });
5004 while (*captureResult == EAGAIN) {
5005 captureResult.reset();
5006 result = postMessageAsync(message);
5007 if (result != NO_ERROR) {
5008 return result;
5009 }
5010 captureCondition.wait(captureLock, [&]() { return captureResult; });
5011 }
5012 result = *captureResult;
5013 }
5014
5015 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005016 sync_wait(syncFd, -1);
5017 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005018 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005019
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005020 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005021}
5022
chaviwa76b2712017-09-20 12:02:26 -07005023void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
5024 TraverseLayersFunction traverseLayers, bool yswap,
5025 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005026 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005027
Lloyd Pique144e1162017-12-20 16:44:52 -08005028 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005029
5030 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005031 const auto raWidth = renderArea.getWidth();
5032 const auto raHeight = renderArea.getHeight();
5033
5034 const auto reqWidth = renderArea.getReqWidth();
5035 const auto reqHeight = renderArea.getReqHeight();
5036 Rect sourceCrop = renderArea.getSourceCrop();
5037
5038 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5039 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005040
Dan Stozac1879002014-05-22 15:59:05 -07005041 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005042 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005043 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005044 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07005045 }
5046
5047 // ensure that sourceCrop is inside screen
5048 if (sourceCrop.left < 0) {
5049 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5050 }
chaviwa76b2712017-09-20 12:02:26 -07005051 if (sourceCrop.right > raWidth) {
5052 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005053 }
5054 if (sourceCrop.top < 0) {
5055 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5056 }
chaviwa76b2712017-09-20 12:02:26 -07005057 if (sourceCrop.bottom > raHeight) {
5058 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005059 }
5060
Peiyong Lin34beb7a2018-03-28 11:57:12 -07005061 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005062 if (renderArea.getWideColorSupport()) {
5063 outputDataspace = renderArea.getDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08005064 }
Peiyong Linfb069302018-04-25 14:34:31 -07005065 engine.setOutputDataSpace(outputDataspace);
5066 engine.setDisplayMaxLuminance(renderArea.getDisplayMaxLuminance());
Romain Guy88d37dd2017-05-26 17:57:05 -07005067
Mathias Agopian180f10d2013-04-10 22:55:41 -07005068 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005069 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005070
5071 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005072 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
5073 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07005074 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005075
chaviw50da5042018-04-09 13:49:37 -07005076 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005077 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005078 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005079
chaviwa76b2712017-09-20 12:02:26 -07005080 traverseLayers([&](Layer* layer) {
5081 if (filtering) layer->setFiltering(true);
5082 layer->draw(renderArea, useIdentityTransform);
5083 if (filtering) layer->setFiltering(false);
5084 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005085}
5086
chaviwa76b2712017-09-20 12:02:26 -07005087status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5088 TraverseLayersFunction traverseLayers,
5089 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005090 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005091 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005092 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005093 ATRACE_CALL();
5094
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005095 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005096
5097 traverseLayers([&](Layer* layer) {
5098 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5099 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005100
Robert Carr03480e22018-01-04 16:02:06 -08005101 // We allow the system server to take screenshots of secure layers for
5102 // use in situations like the Screen-rotation animation and place
5103 // the impetus on WindowManager to not persist them.
5104 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005105 ALOGW("FB is protected: PERMISSION_DENIED");
5106 return PERMISSION_DENIED;
5107 }
5108
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005109 // this binds the given EGLImage as a framebuffer for the
5110 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005111 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005112 if (bufferBond.getStatus() != NO_ERROR) {
5113 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005114 return INVALID_OPERATION;
5115 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005116
Dan Stozaabcda352017-06-01 14:37:39 -07005117 // this will in fact render into our dequeued buffer
5118 // via an FBO, which means we didn't have to create
5119 // an EGLSurface and therefore we're not
5120 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005121 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005122
Dan Stozaabcda352017-06-01 14:37:39 -07005123 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005124 getRenderEngine().finish();
5125 *outSyncFd = -1;
5126
chaviwa76b2712017-09-20 12:02:26 -07005127 const auto reqWidth = renderArea.getReqWidth();
5128 const auto reqHeight = renderArea.getReqHeight();
5129
Dan Stozaabcda352017-06-01 14:37:39 -07005130 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5131 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005132 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005133 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005134 } else {
5135 base::unique_fd syncFd = getRenderEngine().flush();
5136 if (syncFd < 0) {
5137 getRenderEngine().finish();
5138 }
5139 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005140 }
5141
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005142 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005143}
5144
Mathias Agopiand5556842013-09-19 17:08:37 -07005145void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005146 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005147 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005148 for (size_t y = 0; y < h; y++) {
5149 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5150 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005151 if (p[x] != 0xFF000000) return;
5152 }
5153 }
chaviwa76b2712017-09-20 12:02:26 -07005154 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005155
Robert Carr2047fae2016-11-28 14:09:09 -08005156 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005157 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005158 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005159 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5160 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5161 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5162 static_cast<float>(state.color.a));
5163 i++;
5164 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005165 }
5166}
5167
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005168// ---------------------------------------------------------------------------
5169
Dan Stoza412903f2017-04-27 13:42:17 -07005170void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5171 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005172}
5173
Dan Stoza412903f2017-04-27 13:42:17 -07005174void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5175 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005176}
5177
chaviwa76b2712017-09-20 12:02:26 -07005178void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
5179 int32_t maxLayerZ,
5180 const LayerVector::Visitor& visitor) {
5181 // We loop through the first level of layers without traversing,
5182 // as we need to interpret min/max layer Z in the top level Z space.
5183 for (const auto& layer : mDrawingState.layersSortedByZ) {
5184 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5185 continue;
5186 }
5187 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005188 // relative layers are traversed in Layer::traverseInZOrder
5189 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005190 continue;
5191 }
5192 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005193 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5194 return;
5195 }
chaviwa76b2712017-09-20 12:02:26 -07005196 if (!layer->isVisible()) {
5197 return;
5198 }
5199 visitor(layer);
5200 });
5201 }
5202}
5203
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005204}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005205
5206
5207#if defined(__gl_h_)
5208#error "don't include gl/gl.h in this file"
5209#endif
5210
5211#if defined(__gl2_h_)
5212#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005213#endif