blob: abd3a9efcca3adc4cb611001e47d241986202c3b [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 Lin0e7a7912018-04-05 14:36:36 -0700109using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900110
Steven Thomasb02664d2017-07-26 18:48:28 -0700111namespace {
112class ConditionalLock {
113public:
114 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
115 if (lock) {
116 mMutex.lock();
117 }
118 }
119 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
120private:
121 Mutex& mMutex;
122 bool mLocked;
123};
124} // namespace anonymous
125
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800126// ---------------------------------------------------------------------------
127
Mathias Agopian99b49842011-06-27 16:05:52 -0700128const String16 sHardwareTest("android.permission.HARDWARE_TEST");
129const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
130const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
131const String16 sDump("android.permission.DUMP");
132
133// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800134int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
135int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700136int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700137bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800138uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800139bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800140bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800141int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800142// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600143bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700144
Kalle Raitaa099a242017-01-11 11:17:29 -0800145
146std::string getHwcServiceName() {
147 char value[PROPERTY_VALUE_MAX] = {};
148 property_get("debug.sf.hwc_service_name", value, "default");
149 ALOGI("Using HWComposer service: '%s'", value);
150 return std::string(value);
151}
152
153bool useTrebleTestingOverride() {
154 char value[PROPERTY_VALUE_MAX] = {};
155 property_get("debug.sf.treble_testing_override", value, "false");
156 ALOGI("Treble testing override: '%s'", value);
157 return std::string(value) == "true";
158}
159
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800160DisplayColorSetting toDisplayColorSetting(int value) {
161 switch(value) {
162 case 0:
163 return DisplayColorSetting::MANAGED;
164 case 1:
165 return DisplayColorSetting::UNMANAGED;
166 case 2:
167 return DisplayColorSetting::ENHANCED;
168 default:
169 return DisplayColorSetting::MANAGED;
170 }
171}
172
173std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
174 switch(displayColorSetting) {
175 case DisplayColorSetting::MANAGED:
176 return std::string("Natural Mode");
177 case DisplayColorSetting::UNMANAGED:
178 return std::string("Saturated Mode");
179 case DisplayColorSetting::ENHANCED:
180 return std::string("Auto Color Mode");
181 }
182 return std::string("Unknown Display Color Setting");
183}
184
Lloyd Pique09594832018-01-22 17:48:03 -0800185NativeWindowSurface::~NativeWindowSurface() = default;
186
187namespace impl {
188
189class NativeWindowSurface final : public android::NativeWindowSurface {
190public:
191 static std::unique_ptr<android::NativeWindowSurface> create(
192 const sp<IGraphicBufferProducer>& producer) {
193 return std::make_unique<NativeWindowSurface>(producer);
194 }
195
196 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
197 : surface(new Surface(producer, false)) {}
198
199 ~NativeWindowSurface() override = default;
200
201private:
202 sp<ANativeWindow> getNativeWindow() const override { return surface; }
203
204 void preallocateBuffers() override { surface->allocateBuffers(); }
205
206 sp<Surface> surface;
207};
208
209} // namespace impl
210
David Sodmanbc815282017-11-05 18:57:52 -0800211SurfaceFlingerBE::SurfaceFlingerBE()
212 : mHwcServiceName(getHwcServiceName()),
213 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800214 mFrameBuckets(),
215 mTotalTime(0),
216 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800217 mComposerSequenceId(0) {
218}
219
Lloyd Pique2d3ee6d2018-01-17 13:42:24 -0800220SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800221 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800222 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700223 mTransactionPending(false),
224 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700225 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700226 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700227 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800228 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800229 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800230 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800231 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800232 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800233 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700234 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700235 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700236 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700237 mDebugInSwapBuffers(0),
238 mLastSwapBufferTime(0),
239 mDebugInTransaction(0),
240 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700241 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700242 mForceFullDamage(false),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000243 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700244 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700245 mHWVsyncAvailable(false),
Romain Guya9638732017-06-01 12:05:21 -0700246 mHasColorMatrix(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
Mathias Agopian3f844832013-08-07 21:24:32 -0700479void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700480 class MessageDestroyGLTexture : public MessageBase {
Lloyd Pique144e1162017-12-20 16:44:52 -0800481 RE::RenderEngine& engine;
Mathias Agopian3f844832013-08-07 21:24:32 -0700482 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700483 public:
Lloyd Pique144e1162017-12-20 16:44:52 -0800484 MessageDestroyGLTexture(RE::RenderEngine& engine, uint32_t texture)
485 : engine(engine), texture(texture) {}
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700486 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700487 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700488 return true;
489 }
490 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700491 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700492}
493
Lloyd Piquee83f9312018-02-01 12:53:17 -0800494class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700495public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700496 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000497 const char* name) :
498 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700499 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700500 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000501 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
502 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700503 mDispSync(dispSync),
504 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700505 mVsyncMutex(),
506 mPhaseOffset(phaseOffset),
507 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700508
Lloyd Piquee83f9312018-02-01 12:53:17 -0800509 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700510
Lloyd Piquee83f9312018-02-01 12:53:17 -0800511 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700512 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700513 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000514 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700515 static_cast<DispSync::Callback*>(this));
516 if (err != NO_ERROR) {
517 ALOGE("error registering vsync callback: %s (%d)",
518 strerror(-err), err);
519 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700520 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700521 } else {
522 status_t err = mDispSync->removeEventListener(
523 static_cast<DispSync::Callback*>(this));
524 if (err != NO_ERROR) {
525 ALOGE("error unregistering vsync callback: %s (%d)",
526 strerror(-err), err);
527 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700528 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700529 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700530 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700531 }
532
Lloyd Piquee83f9312018-02-01 12:53:17 -0800533 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700534 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700535 mCallback = callback;
536 }
537
Lloyd Piquee83f9312018-02-01 12:53:17 -0800538 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700539 Mutex::Autolock lock(mVsyncMutex);
540
541 // Normalize phaseOffset to [0, period)
542 auto period = mDispSync->getPeriod();
543 phaseOffset %= period;
544 if (phaseOffset < 0) {
545 // If we're here, then phaseOffset is in (-period, 0). After this
546 // operation, it will be in (0, period)
547 phaseOffset += period;
548 }
549 mPhaseOffset = phaseOffset;
550
551 // If we're not enabled, we don't need to mess with the listeners
552 if (!mEnabled) {
553 return;
554 }
555
Dan Stoza2713c302018-03-28 17:07:36 -0700556 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
557 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700558 if (err != NO_ERROR) {
Dan Stoza2713c302018-03-28 17:07:36 -0700559 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700560 strerror(-err), err);
561 }
562 }
563
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700564private:
565 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800566 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700567 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700568 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700569 callback = mCallback;
570
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700571 if (mTraceVsync) {
572 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700573 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700574 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700575 }
576
Peiyong Lin566a3b42018-01-09 18:22:43 -0800577 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700578 callback->onVSyncEvent(when);
579 }
580 }
581
Tim Murray4a4e4a22016-04-19 16:29:23 +0000582 const char* const mName;
583
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700584 int mValue;
585
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700586 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700587 const String8 mVsyncOnLabel;
588 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700589
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700590 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700591
592 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800593 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700594
595 Mutex mVsyncMutex; // Protects the following
596 nsecs_t mPhaseOffset;
597 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700598};
599
Lloyd Piquee83f9312018-02-01 12:53:17 -0800600class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700601public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800602 InjectVSyncSource() = default;
603 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700604
Lloyd Piquee83f9312018-02-01 12:53:17 -0800605 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700606 std::lock_guard<std::mutex> lock(mCallbackMutex);
607 mCallback = callback;
608 }
609
Lloyd Piquee83f9312018-02-01 12:53:17 -0800610 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700611 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700612 if (mCallback) {
613 mCallback->onVSyncEvent(when);
614 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700615 }
616
Lloyd Piquee83f9312018-02-01 12:53:17 -0800617 void setVSyncEnabled(bool) override {}
618 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700619
620private:
621 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800622 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700623};
624
Wei Wangf9b05ee2017-07-19 20:59:39 -0700625// Do not call property_set on main thread which will be blocked by init
626// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700627void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700628 ALOGI( "SurfaceFlinger's main thread ready to run. "
629 "Initializing graphics H/W...");
630
Thierry Strudel2924d012017-08-14 15:19:37 -0700631 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900632
Steven Thomasb02664d2017-07-26 18:48:28 -0700633 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800634
Steven Thomasb02664d2017-07-26 18:48:28 -0700635 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800636 mEventThreadSource =
637 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
638 true, "app");
639 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(), *this, false,
640 "appEventThread");
641 mSfEventThreadSource =
642 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
643 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800644
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800645 mSFEventThread = std::make_unique<impl::EventThread>(mSfEventThreadSource.get(), *this, true,
646 "sfEventThread");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800647 mEventQueue->setEventThread(mSFEventThread.get());
Dan Stoza2713c302018-03-28 17:07:36 -0700648 mVsyncModulator.setEventThread(mSFEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800649
Steven Thomasb02664d2017-07-26 18:48:28 -0700650 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800651 getBE().mRenderEngine =
652 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
653 hasWideColorDisplay
654 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
655 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800656 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700657
658 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
659 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800660 getBE().mHwc.reset(
661 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700662 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800663 // Process any initial hotplug and resulting display changes.
664 processDisplayHotplugEventsLocked();
665 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
666 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800667
Lloyd Piquefcd86612017-12-14 17:15:36 -0800668 // make the default display GLContext current so that we can create textures
669 // when creating Layers (which may happens before we render something)
670 getDefaultDisplayDeviceLocked()->makeCurrent();
671
Steven Thomas050b2c82017-03-06 11:45:16 -0800672 if (useVrFlinger) {
673 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700674 // This callback is called from the vr flinger dispatch thread. We
675 // need to call signalTransaction(), which requires holding
676 // mStateLock when we're not on the main thread. Acquiring
677 // mStateLock from the vr flinger dispatch thread might trigger a
678 // deadlock in surface flinger (see b/66916578), so post a message
679 // to be handled on the main thread instead.
680 sp<LambdaMessage> message = new LambdaMessage([=]() {
681 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
682 mVrFlingerRequestsDisplay = requestDisplay;
683 signalTransaction();
684 });
685 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800686 };
David Sodman105b7dc2017-11-04 20:28:14 -0700687 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
688 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800689 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800690 if (!mVrFlinger) {
691 ALOGE("Failed to start vrflinger");
692 }
693 }
694
Lloyd Pique0c3a8832018-01-22 17:31:47 -0800695 mEventControlThread = std::make_unique<impl::EventControlThread>(
696 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700697
Mathias Agopian92a979a2012-08-02 18:32:23 -0700698 // initialize our drawing state
699 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700700
Andy McFadden13a082e2012-08-24 10:16:42 -0700701 // set initial conditions (e.g. unblank default device)
702 initializeDisplays();
703
David Sodmanbc815282017-11-05 18:57:52 -0800704 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700705
Wei Wangf9b05ee2017-07-19 20:59:39 -0700706 // Inform native graphics APIs whether the present timestamp is supported:
707 if (getHwComposer().hasCapability(
708 HWC2::Capability::PresentFenceIsNotReliable)) {
709 mStartPropertySetThread = new StartPropertySetThread(false);
710 } else {
711 mStartPropertySetThread = new StartPropertySetThread(true);
712 }
713
714 if (mStartPropertySetThread->Start() != NO_ERROR) {
715 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800716 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800717
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800718 mLegacySrgbSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(HWC_DISPLAY_PRIMARY,
719 Dataspace::SRGB_LINEAR);
720
Dan Stoza9e56aa02015-11-02 13:00:03 -0800721 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700722}
723
Romain Guy11d63f42017-07-20 12:47:14 -0700724void SurfaceFlinger::readPersistentProperties() {
725 char value[PROPERTY_VALUE_MAX];
726
727 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800728 mGlobalSaturationFactor = atof(value);
729 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100730
731 property_get("persist.sys.sf.native_mode", value, "0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800732 mDisplayColorSetting = toDisplayColorSetting(atoi(value));
733 ALOGV("Display Color Setting is set to %s.",
734 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Romain Guy11d63f42017-07-20 12:47:14 -0700735}
736
Mathias Agopiana67e4182012-06-19 17:26:12 -0700737void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800738 // Start boot animation service by setting a property mailbox
739 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700740 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800741 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700742 if (mStartPropertySetThread->join() != NO_ERROR) {
743 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800744 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700745}
746
Mathias Agopian875d8e12013-06-07 15:35:48 -0700747size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800748 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700749}
750
Mathias Agopian875d8e12013-06-07 15:35:48 -0700751size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800752 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700753}
754
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800755// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800756
Jamie Gennis582270d2011-08-17 18:19:00 -0700757bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800758 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800759 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800760 return authenticateSurfaceTextureLocked(bufferProducer);
761}
762
763bool SurfaceFlinger::authenticateSurfaceTextureLocked(
764 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800765 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800766 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800767}
768
Brian Anderson6b376712017-04-04 10:51:39 -0700769status_t SurfaceFlinger::getSupportedFrameTimestamps(
770 std::vector<FrameEvent>* outSupported) const {
771 *outSupported = {
772 FrameEvent::REQUESTED_PRESENT,
773 FrameEvent::ACQUIRE,
774 FrameEvent::LATCH,
775 FrameEvent::FIRST_REFRESH_START,
776 FrameEvent::LAST_REFRESH_START,
777 FrameEvent::GPU_COMPOSITION_DONE,
778 FrameEvent::DEQUEUE_READY,
779 FrameEvent::RELEASE,
780 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700781 ConditionalLock _l(mStateLock,
782 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700783 if (!getHwComposer().hasCapability(
784 HWC2::Capability::PresentFenceIsNotReliable)) {
785 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
786 }
787 return NO_ERROR;
788}
789
Dan Stoza7f7da322014-05-02 15:26:25 -0700790status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
791 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800792 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700793 return BAD_VALUE;
794 }
795
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500796 if (!display.get())
797 return NAME_NOT_FOUND;
798
Jesse Hall692c7232012-11-08 15:41:56 -0800799 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700800 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800801 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700802 type = i;
803 break;
804 }
805 }
806
807 if (type < 0) {
808 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700809 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700810
Mathias Agopian8b736f12012-08-13 17:54:26 -0700811 // TODO: Not sure if display density should handled by SF any longer
812 class Density {
813 static int getDensityFromProperty(char const* propName) {
814 char property[PROPERTY_VALUE_MAX];
815 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800816 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700817 density = atoi(property);
818 }
819 return density;
820 }
821 public:
822 static int getEmuDensity() {
823 return getDensityFromProperty("qemu.sf.lcd_density"); }
824 static int getBuildDensity() {
825 return getDensityFromProperty("ro.sf.lcd_density"); }
826 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700827
Dan Stoza7f7da322014-05-02 15:26:25 -0700828 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700829
Steven Thomas6d8110b2017-08-31 18:24:21 -0700830 ConditionalLock _l(mStateLock,
831 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800832 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700833 DisplayInfo info = DisplayInfo();
834
Dan Stoza9e56aa02015-11-02 13:00:03 -0800835 float xdpi = hwConfig->getDpiX();
836 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700837
838 if (type == DisplayDevice::DISPLAY_PRIMARY) {
839 // The density of the device is provided by a build property
840 float density = Density::getBuildDensity() / 160.0f;
841 if (density == 0) {
842 // the build doesn't provide a density -- this is wrong!
843 // use xdpi instead
844 ALOGE("ro.sf.lcd_density must be defined as a build property");
845 density = xdpi / 160.0f;
846 }
847 if (Density::getEmuDensity()) {
848 // if "qemu.sf.lcd_density" is specified, it overrides everything
849 xdpi = ydpi = density = Density::getEmuDensity();
850 density /= 160.0f;
851 }
852 info.density = density;
853
854 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700855 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800856 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700857 } else {
858 // TODO: where should this value come from?
859 static const int TV_DENSITY = 213;
860 info.density = TV_DENSITY / 160.0f;
861 info.orientation = 0;
862 }
863
Dan Stoza9e56aa02015-11-02 13:00:03 -0800864 info.w = hwConfig->getWidth();
865 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700866 info.xdpi = xdpi;
867 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800868 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900869 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800870
Andy McFadden91b2ca82014-06-13 14:04:23 -0700871 // This is how far in advance a buffer must be queued for
872 // presentation at a given time. If you want a buffer to appear
873 // on the screen at time N, you must submit the buffer before
874 // (N - presentationDeadline).
875 //
876 // Normally it's one full refresh period (to give SF a chance to
877 // latch the buffer), but this can be reduced by configuring a
878 // DispSync offset. Any additional delays introduced by the hardware
879 // composer or panel must be accounted for here.
880 //
881 // We add an additional 1ms to allow for processing time and
882 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800883 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800884 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700885
886 // All non-virtual displays are currently considered secure.
887 info.secure = true;
888
Michael Wright28f24d02016-07-12 13:30:53 -0700889 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700890 }
891
Dan Stoza7f7da322014-05-02 15:26:25 -0700892 return NO_ERROR;
893}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700894
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800895status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700896 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800897 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700898 return BAD_VALUE;
899 }
900
901 // FIXME for now we always return stats for the primary display
902 memset(stats, 0, sizeof(*stats));
903 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
904 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
905 return NO_ERROR;
906}
907
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700908int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800909 if (display == nullptr) {
910 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800911 return BAD_VALUE;
912 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700913
914 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800915 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700916 return device->getActiveConfig();
917 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700918
Dan Stoza24a42e92015-03-09 10:04:11 -0700919 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700920}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700921
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700922void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
923 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
924 this);
925 int32_t type = hw->getDisplayType();
926 int currentMode = hw->getActiveConfig();
927
928 if (mode == currentMode) {
929 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
930 return;
931 }
932
933 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
934 ALOGW("Trying to set config for virtual display");
935 return;
936 }
937
938 hw->setActiveConfig(mode);
939 getHwComposer().setActiveConfig(type, mode);
940}
941
942status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
943 class MessageSetActiveConfig: public MessageBase {
944 SurfaceFlinger& mFlinger;
945 sp<IBinder> mDisplay;
946 int mMode;
947 public:
948 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
949 int mode) :
950 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
951 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700952 Vector<DisplayInfo> configs;
953 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700954 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700955 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700956 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700957 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700958 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700959 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800960 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700961 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700962 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700963 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
964 ALOGW("Attempt to set active config = %d for virtual display",
965 mMode);
966 } else {
967 mFlinger.setActiveConfigInternal(hw, mMode);
968 }
969 return true;
970 }
971 };
972 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
973 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700974 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700975}
Michael Wright28f24d02016-07-12 13:30:53 -0700976status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -0700977 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700978 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
979 return BAD_VALUE;
980 }
981
982 if (!display.get()) {
983 return NAME_NOT_FOUND;
984 }
985
986 int32_t type = NAME_NOT_FOUND;
987 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
988 if (display == mBuiltinDisplays[i]) {
989 type = i;
990 break;
991 }
992 }
993
994 if (type < 0) {
995 return type;
996 }
997
Peiyong Lina52f0292018-03-14 17:26:31 -0700998 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700999 {
1000 ConditionalLock _l(mStateLock,
1001 std::this_thread::get_id() != mMainThreadId);
1002 modes = getHwComposer().getColorModes(type);
1003 }
Michael Wright28f24d02016-07-12 13:30:53 -07001004 outColorModes->clear();
1005 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1006
1007 return NO_ERROR;
1008}
1009
Peiyong Lina52f0292018-03-14 17:26:31 -07001010ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001011 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -07001012 if (device != nullptr) {
1013 return device->getActiveColorMode();
1014 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001015 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001016}
1017
1018void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001019 ColorMode mode, Dataspace dataSpace) {
Michael Wright28f24d02016-07-12 13:30:53 -07001020 int32_t type = hw->getDisplayType();
Peiyong Lina52f0292018-03-14 17:26:31 -07001021 ColorMode currentMode = hw->getActiveColorMode();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001022 Dataspace currentDataSpace = hw->getCompositionDataSpace();
Michael Wright28f24d02016-07-12 13:30:53 -07001023
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001024 if (mode == currentMode && dataSpace == currentDataSpace) {
Michael Wright28f24d02016-07-12 13:30:53 -07001025 return;
1026 }
1027
1028 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1029 ALOGW("Trying to set config for virtual display");
1030 return;
1031 }
1032
1033 hw->setActiveColorMode(mode);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001034 hw->setCompositionDataSpace(dataSpace);
1035 // Natural Mode means it's color managed and the color must be right,
1036 // thus we pick RenderIntent::COLORIMETRIC as render intent.
1037 // Native Mode means the display is not color managed, and whichever
1038 // render intent is picked doesn't matter, thus return
1039 // RenderIntent::COLORIMETRIC as default here.
1040 RenderIntent renderIntent = RenderIntent::COLORIMETRIC;
1041
1042 // In Auto Color Mode, we want to strech to panel color space, right now
1043 // only the built-in display supports it.
1044 if (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
1045 mBuiltinDisplaySupportsEnhance &&
1046 hw->getDisplayType() == DisplayDevice::DISPLAY_PRIMARY) {
1047 renderIntent = RenderIntent::ENHANCE;
1048 }
1049 hw->setActiveRenderIntent(renderIntent);
1050 getHwComposer().setActiveColorMode(type, mode, renderIntent);
1051
1052 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
1053 decodeColorMode(mode).c_str(), mode,
1054 decodeRenderIntent(renderIntent).c_str(), renderIntent,
1055 hw->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001056}
1057
1058
1059status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001060 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -07001061 class MessageSetActiveColorMode: public MessageBase {
1062 SurfaceFlinger& mFlinger;
1063 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -07001064 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001065 public:
1066 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -07001067 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -07001068 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1069 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -07001070 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001071 mFlinger.getDisplayColorModes(mDisplay, &modes);
1072 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -07001073 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001074 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1075 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001076 return true;
1077 }
1078 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1079 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001080 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1081 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001082 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001083 ALOGW("Attempt to set active color mode %s %d for virtual display",
1084 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001085 } else {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001086 mFlinger.setActiveColorModeInternal(hw, mMode, Dataspace::UNKNOWN);
Michael Wright28f24d02016-07-12 13:30:53 -07001087 }
1088 return true;
1089 }
1090 };
1091 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1092 postMessageSync(msg);
1093 return NO_ERROR;
1094}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001095
Svetoslavd85084b2014-03-20 10:28:31 -07001096status_t SurfaceFlinger::clearAnimationFrameStats() {
1097 Mutex::Autolock _l(mStateLock);
1098 mAnimFrameTracker.clearStats();
1099 return NO_ERROR;
1100}
1101
1102status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1103 Mutex::Autolock _l(mStateLock);
1104 mAnimFrameTracker.getStats(outStats);
1105 return NO_ERROR;
1106}
1107
Dan Stozac4f471e2016-03-24 09:31:08 -07001108status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1109 HdrCapabilities* outCapabilities) const {
1110 Mutex::Autolock _l(mStateLock);
1111
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001112 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001113 if (displayDevice == nullptr) {
1114 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1115 return BAD_VALUE;
1116 }
1117
1118 std::unique_ptr<HdrCapabilities> capabilities =
David Sodman105b7dc2017-11-04 20:28:14 -07001119 getBE().mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
Dan Stozac4f471e2016-03-24 09:31:08 -07001120 if (capabilities) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001121 if (displayDevice->hasWideColorGamut() && !displayDevice->hasHdr10()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001122 // insert HDR10 as we will force client composition for HDR10
1123 // layers
1124 std::vector<int32_t> types = capabilities->getSupportedHdrTypes();
1125 types.push_back(HAL_HDR_HDR10);
1126
1127 *outCapabilities = HdrCapabilities(types,
1128 capabilities->getDesiredMaxLuminance(),
1129 capabilities->getDesiredMaxAverageLuminance(),
1130 capabilities->getDesiredMinLuminance());
1131 } else {
1132 *outCapabilities = std::move(*capabilities);
1133 }
Dan Stozac4f471e2016-03-24 09:31:08 -07001134 } else {
1135 return BAD_VALUE;
1136 }
1137
1138 return NO_ERROR;
1139}
1140
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001141status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001142 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1143 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001144
Chia-I Wu90f669f2017-10-05 14:24:41 -07001145 if (mInjectVSyncs == enable) {
1146 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001147 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001148
1149 if (enable) {
1150 ALOGV("VSync Injections enabled");
1151 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001152 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique0fcde1b2017-12-20 16:50:21 -08001153 mInjectorEventThread =
1154 std::make_unique<impl::EventThread>(mVSyncInjector.get(), *this, false,
1155 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001156 }
Lloyd Pique9123ae52018-01-22 17:14:00 -08001157 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001158 } else {
1159 ALOGV("VSync Injections disabled");
Lloyd Pique9123ae52018-01-22 17:14:00 -08001160 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001161 }
1162
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001163 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001164 });
1165 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001166 return NO_ERROR;
1167}
1168
1169status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001170 Mutex::Autolock _l(mStateLock);
1171
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001172 if (!mInjectVSyncs) {
1173 ALOGE("VSync Injections not enabled");
1174 return BAD_VALUE;
1175 }
1176 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1177 ALOGV("Injecting VSync inside SurfaceFlinger");
1178 mVSyncInjector->onInjectSyncEvent(when);
1179 }
1180 return NO_ERROR;
1181}
1182
Lloyd Pique755e3192018-01-31 16:46:15 -08001183status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1184 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001185 IPCThreadState* ipc = IPCThreadState::self();
1186 const int pid = ipc->getCallingPid();
1187 const int uid = ipc->getCallingUid();
1188 if ((uid != AID_SHELL) &&
1189 !PermissionCache::checkPermission(sDump, pid, uid)) {
1190 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1191 return PERMISSION_DENIED;
1192 }
1193
1194 // Try to acquire a lock for 1s, fail gracefully
1195 const status_t err = mStateLock.timedLock(s2ns(1));
1196 const bool locked = (err == NO_ERROR);
1197 if (!locked) {
1198 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1199 return TIMED_OUT;
1200 }
1201
1202 outLayers->clear();
1203 mCurrentState.traverseInZOrder([&](Layer* layer) {
1204 outLayers->push_back(layer->getLayerDebugInfo());
1205 });
1206
1207 mStateLock.unlock();
1208 return NO_ERROR;
1209}
1210
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001211// ----------------------------------------------------------------------------
1212
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001213sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1214 ISurfaceComposer::VsyncSource vsyncSource) {
1215 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1216 return mSFEventThread->createEventConnection();
1217 } else {
1218 return mEventThread->createEventConnection();
1219 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001220}
1221
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001222// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001223
1224void SurfaceFlinger::waitForEvent() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001225 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001226}
1227
1228void SurfaceFlinger::signalTransaction() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001229 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001230}
1231
1232void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001233 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001234}
1235
1236void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001237 mRefreshPending = true;
Lloyd Pique9123ae52018-01-22 17:14:00 -08001238 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001239}
1240
1241status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001242 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001243 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001244}
1245
1246status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001247 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001248 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001249 if (res == NO_ERROR) {
1250 msg->wait();
1251 }
1252 return res;
1253}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001254
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001255void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001256 do {
1257 waitForEvent();
1258 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001259}
1260
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001261void SurfaceFlinger::enableHardwareVsync() {
1262 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001263 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001264 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001265 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1266 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001267 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001268 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001269}
1270
Jesse Hall948fe0c2013-10-14 12:56:09 -07001271void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001272 Mutex::Autolock _l(mHWVsyncLock);
1273
Jesse Hall948fe0c2013-10-14 12:56:09 -07001274 if (makeAvailable) {
1275 mHWVsyncAvailable = true;
1276 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001277 // Hardware vsync is not currently available, so abort the resync
1278 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001279 return;
1280 }
1281
David Sodman105b7dc2017-11-04 20:28:14 -07001282 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001283 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001284
1285 mPrimaryDispSync.reset();
1286 mPrimaryDispSync.setPeriod(period);
1287
1288 if (!mPrimaryHWVsyncEnabled) {
1289 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001290 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1291 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001292 mPrimaryHWVsyncEnabled = true;
1293 }
1294}
1295
Jesse Hall948fe0c2013-10-14 12:56:09 -07001296void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001297 Mutex::Autolock _l(mHWVsyncLock);
1298 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001299 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1300 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001301 mPrimaryDispSync.endResync();
1302 mPrimaryHWVsyncEnabled = false;
1303 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001304 if (makeUnavailable) {
1305 mHWVsyncAvailable = false;
1306 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001307}
1308
Tim Murray4a4e4a22016-04-19 16:29:23 +00001309void SurfaceFlinger::resyncWithRateLimit() {
1310 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001311
1312 // No explicit locking is needed here since EventThread holds a lock while calling this method
1313 static nsecs_t sLastResyncAttempted = 0;
1314 const nsecs_t now = systemTime();
1315 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001316 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001317 }
Dan Stoza57164302017-05-08 14:03:54 -07001318 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001319}
1320
Steven Thomasb02664d2017-07-26 18:48:28 -07001321void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1322 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001323 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001324 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001325 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001326 return;
1327 }
1328
1329 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001330 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001331 return;
1332 }
1333
Jamie Gennisd1700752013-10-14 12:22:52 -07001334 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001335
Jamie Gennisd1700752013-10-14 12:22:52 -07001336 { // Scope for the lock
1337 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001338 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001339 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001340 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001341 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001342
1343 if (needsHwVsync) {
1344 enableHardwareVsync();
1345 } else {
1346 disableHardwareVsync(false);
1347 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001348}
1349
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001350void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001351 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1352 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001353}
1354
Lloyd Pique715a2c12017-12-14 17:18:08 -08001355void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1356 HWC2::Connection connection) {
1357 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1358 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001359
Lloyd Piqueba04e622017-12-14 17:11:26 -08001360 // Ignore events that do not have the right sequenceId.
1361 if (sequenceId != getBE().mComposerSequenceId) {
1362 return;
1363 }
1364
Steven Thomasb02664d2017-07-26 18:48:28 -07001365 // Only lock if we're not on the main thread. This function is normally
1366 // called on a hwbinder thread, but for the primary display it's called on
1367 // the main thread with the state lock already held, so don't attempt to
1368 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001369 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001370
Lloyd Pique715a2c12017-12-14 17:18:08 -08001371 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001372
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001373 if (std::this_thread::get_id() == mMainThreadId) {
1374 // Process all pending hot plug events immediately if we are on the main thread.
1375 processDisplayHotplugEventsLocked();
1376 }
1377
Lloyd Piqueba04e622017-12-14 17:11:26 -08001378 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001379}
1380
Steven Thomasb02664d2017-07-26 18:48:28 -07001381void SurfaceFlinger::onRefreshReceived(int sequenceId,
1382 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001383 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001384 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001385 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001386 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001387 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001388}
1389
Dan Stoza9e56aa02015-11-02 13:00:03 -08001390void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001391 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001392 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001393 getHwComposer().setVsyncEnabled(disp,
1394 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001395}
1396
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001397// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001398void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001399 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001400 // Clear the drawing state so that the logic inside of
1401 // handleTransactionLocked will fire. It will determine the delta between
1402 // mCurrentState and mDrawingState and re-apply all changes when we make the
1403 // transition.
1404 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001405 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001406 mDisplays.clear();
1407}
1408
Steven Thomas050b2c82017-03-06 11:45:16 -08001409void SurfaceFlinger::updateVrFlinger() {
1410 if (!mVrFlinger)
1411 return;
1412 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001413 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001414 return;
1415 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001416
David Sodman105b7dc2017-11-04 20:28:14 -07001417 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001418 ALOGE("Vr flinger is only supported for remote hardware composer"
1419 " service connections. Ignoring request to transition to vr"
1420 " flinger.");
1421 mVrFlingerRequestsDisplay = false;
1422 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001423 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001424
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001425 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001426
Steven Thomasb02664d2017-07-26 18:48:28 -07001427 int currentDisplayPowerMode = getDisplayDeviceLocked(
1428 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001429
Steven Thomasb02664d2017-07-26 18:48:28 -07001430 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001431 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001432 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001433
Steven Thomasb02664d2017-07-26 18:48:28 -07001434 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001435 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001436 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1437 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001438 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001439
David Sodman105b7dc2017-11-04 20:28:14 -07001440 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1441 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001442
1443 if (vrFlingerRequestsDisplay) {
1444 mVrFlinger->GrantDisplayOwnership();
1445 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001446 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001447 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001448
1449 mVisibleRegionsDirty = true;
1450 invalidateHwcGeometry();
1451
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001452 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001453 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1454 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1455 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001456
Steven Thomasb02664d2017-07-26 18:48:28 -07001457 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001458 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001459 const nsecs_t period = activeConfig->getVsyncPeriod();
1460 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001461
Steven Thomasb02664d2017-07-26 18:48:28 -07001462 // Use phase of 0 since phase is not known.
1463 // Use latency of 0, which will snap to the ideal latency.
1464 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001465
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001466 android_atomic_or(1, &mRepaintEverything);
1467 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001468}
1469
Mathias Agopian4fec8732012-06-29 14:12:52 -07001470void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001471 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001472 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001473 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001474 bool frameMissed = !mHadClientComposition &&
1475 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001476 (mPreviousPresentFence->getSignalTime() ==
1477 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001478 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001479 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001480 signalLayerUpdate();
1481 break;
1482 }
1483
Steven Thomas050b2c82017-03-06 11:45:16 -08001484 // Now that we're going to make it to the handleMessageTransaction()
1485 // call below it's safe to call updateVrFlinger(), which will
1486 // potentially trigger a display handoff.
1487 updateVrFlinger();
1488
Dan Stoza6b9454d2014-11-07 16:00:59 -08001489 bool refreshNeeded = handleMessageTransaction();
1490 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001491 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001492 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001493 // Signal a refresh if a transaction modified the window state,
1494 // a new buffer was latched, or if HWC has requested a full
1495 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001496 signalRefresh();
1497 }
1498 break;
1499 }
1500 case MessageQueue::REFRESH: {
1501 handleMessageRefresh();
1502 break;
1503 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001504 }
1505}
1506
Dan Stoza6b9454d2014-11-07 16:00:59 -08001507bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001508 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001509 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001510 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001511 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001512 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001513 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001514}
1515
Dan Stoza6b9454d2014-11-07 16:00:59 -08001516bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001517 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001518 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001519}
1520
1521void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001522 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001523
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001524 mRefreshPending = false;
1525
Pablo Ceballos40845df2016-01-25 17:41:15 -08001526 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001527
Brian Andersond6927fb2016-07-23 23:37:30 -07001528 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001529 rebuildLayerStacks();
1530 setUpHWComposer();
1531 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001532 doTracing("handleRefresh");
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001533 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001534 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001535 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001536
David Sodman105b7dc2017-11-04 20:28:14 -07001537 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001538
1539 mHadClientComposition = false;
1540 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1541 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1542 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001543 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001544 }
Dan Stoza2713c302018-03-28 17:07:36 -07001545 mVsyncModulator.setLastFrameUsedRenderEngine(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001546
Dan Stoza9e56aa02015-11-02 13:00:03 -08001547 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001548}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001549
Mathias Agopiancd60f992012-08-16 16:28:27 -07001550void SurfaceFlinger::doDebugFlashRegions()
1551{
1552 // is debugging enabled
1553 if (CC_LIKELY(!mDebugRegion))
1554 return;
1555
1556 const bool repaintEverything = mRepaintEverything;
1557 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1558 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001559 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001560 // transform the dirty region into this screen's coordinate space
1561 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1562 if (!dirtyRegion.isEmpty()) {
1563 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001564 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001565
1566 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001567 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001568 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001569 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1570
Mathias Agopianda27af92012-09-13 18:17:13 -07001571 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001572 }
1573 }
1574 }
1575
1576 postFramebuffer();
1577
1578 if (mDebugRegion > 1) {
1579 usleep(mDebugRegion * 1000);
1580 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001581
Dan Stoza9e56aa02015-11-02 13:00:03 -08001582 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001583 auto& displayDevice = mDisplays[displayId];
1584 if (!displayDevice->isDisplayOn()) {
1585 continue;
1586 }
1587
David Sodman105b7dc2017-11-04 20:28:14 -07001588 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1589 ALOGE_IF(result != NO_ERROR,
1590 "prepareFrame for display %zd failed:"
1591 " %d (%s)",
1592 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001593 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001594}
1595
Adrian Roos1e1a1282017-11-01 19:05:31 +01001596void SurfaceFlinger::doTracing(const char* where) {
1597 ATRACE_CALL();
1598 ATRACE_NAME(where);
1599 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001600 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001601 }
1602}
1603
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001604void SurfaceFlinger::logLayerStats() {
1605 ATRACE_CALL();
1606 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1607 int32_t hwcId = -1;
1608 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1609 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1610 if (displayDevice->isPrimary()) {
1611 hwcId = displayDevice->getHwcDisplayId();
1612 break;
1613 }
1614 }
1615 if (hwcId < 0) {
1616 ALOGE("LayerStats: Hmmm, no primary display?");
1617 return;
1618 }
1619 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1620 }
1621}
1622
Brian Andersond6927fb2016-07-23 23:37:30 -07001623void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001624{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001625 ATRACE_CALL();
1626 ALOGV("preComposition");
1627
Mathias Agopiancd60f992012-08-16 16:28:27 -07001628 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001629 mDrawingState.traverseInZOrder([&](Layer* layer) {
1630 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001631 needExtraInvalidate = true;
1632 }
Robert Carr2047fae2016-11-28 14:09:09 -08001633 });
1634
Mathias Agopiancd60f992012-08-16 16:28:27 -07001635 if (needExtraInvalidate) {
1636 signalLayerUpdate();
1637 }
1638}
1639
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001640void SurfaceFlinger::updateCompositorTiming(
1641 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1642 std::shared_ptr<FenceTime>& presentFenceTime) {
1643 // Update queue of past composite+present times and determine the
1644 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001645 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001646 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001647 while (!getBE().mCompositePresentTimes.empty()) {
1648 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001649 // Cached values should have been updated before calling this method,
1650 // which helps avoid duplicate syscalls.
1651 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1652 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1653 break;
1654 }
1655 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001656 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001657 }
1658
1659 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001660 while (getBE().mCompositePresentTimes.size() > 16) {
1661 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001662 }
1663
Brian Andersond0010582017-03-07 13:20:31 -08001664 setCompositorTimingSnapped(
1665 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1666}
1667
1668void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1669 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001670 // Integer division and modulo round toward 0 not -inf, so we need to
1671 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001672 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001673 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1674 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1675
Brian Andersond0010582017-03-07 13:20:31 -08001676 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1677 if (idealLatency <= 0) {
1678 idealLatency = vsyncInterval;
1679 }
1680
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001681 // Snap the latency to a value that removes scheduling jitter from the
1682 // composition and present times, which often have >1ms of jitter.
1683 // Reducing jitter is important if an app attempts to extrapolate
1684 // something (such as user input) to an accurate diasplay time.
1685 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1686 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001687 nsecs_t bias = vsyncInterval / 2;
1688 int64_t extraVsyncs =
1689 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1690 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1691 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001692
David Sodman99974d22017-11-28 12:04:33 -08001693 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1694 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1695 getBE().mCompositorTiming.interval = vsyncInterval;
1696 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001697}
1698
1699void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001700{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001701 ATRACE_CALL();
1702 ALOGV("postComposition");
1703
Brian Anderson3546a3f2016-07-14 11:51:14 -07001704 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001705 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001706 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001707 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001708 }
1709
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001710 // |mStateLock| not needed as we are on the main thread
1711 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001712
David Sodman73beded2017-11-15 11:56:06 -08001713 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001714 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001715 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001716 glCompositionDoneFenceTime =
1717 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001718 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001719 } else {
1720 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1721 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001722
David Sodman73beded2017-11-15 11:56:06 -08001723 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001724 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001725 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001726 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001727
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001728 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1729 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1730
1731 // We use the refreshStartTime which might be sampled a little later than
1732 // when we started doing work for this frame, but that should be okay
1733 // since updateCompositorTiming has snapping logic.
1734 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001735 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001736 CompositorTiming compositorTiming;
1737 {
David Sodman99974d22017-11-28 12:04:33 -08001738 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1739 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001740 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001741
Robert Carr2047fae2016-11-28 14:09:09 -08001742 mDrawingState.traverseInZOrder([&](Layer* layer) {
1743 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001744 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001745 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001746 recordBufferingStats(layer->getName().string(),
1747 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001748 }
Robert Carr2047fae2016-11-28 14:09:09 -08001749 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001750
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001751 if (presentFenceTime->isValid()) {
1752 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001753 enableHardwareVsync();
1754 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001755 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001756 }
1757 }
1758
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001759 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001760 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001761 enableHardwareVsync();
1762 }
1763 }
1764
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001765 if (mAnimCompositionPending) {
1766 mAnimCompositionPending = false;
1767
Brian Anderson4e606e32017-03-16 15:34:57 -07001768 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001769 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001770 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001771 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001772 // The HWC doesn't support present fences, so use the refresh
1773 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001774 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001775 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001776 mAnimFrameTracker.setActualPresentTime(presentTime);
1777 }
1778 mAnimFrameTracker.advanceFrame();
1779 }
Dan Stozab90cf072015-03-05 11:05:59 -08001780
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001781 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1782 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001783 return;
1784 }
1785
1786 nsecs_t currentTime = systemTime();
1787 if (mHasPoweredOff) {
1788 mHasPoweredOff = false;
1789 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001790 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001791 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001792 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1793 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001794 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001795 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001796 }
David Sodman4a36e932017-11-07 14:29:47 -08001797 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001798 }
David Sodman4a36e932017-11-07 14:29:47 -08001799 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001800}
1801
1802void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001803 ATRACE_CALL();
1804 ALOGV("rebuildLayerStacks");
1805
Mathias Agopiancd60f992012-08-16 16:28:27 -07001806 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001807 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001808 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001809 mVisibleRegionsDirty = false;
1810 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001811
Jeff Sharkey76488112017-02-27 14:15:18 -07001812 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1813 Region opaqueRegion;
1814 Region dirtyRegion;
1815 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001816 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001817 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1818 const Transform& tr(displayDevice->getTransform());
1819 const Rect bounds(displayDevice->getBounds());
1820 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001821 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001822
Jeff Sharkey76488112017-02-27 14:15:18 -07001823 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001824 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001825 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1826 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001827 Region drawRegion(tr.transform(
1828 layer->visibleNonTransparentRegion));
1829 drawRegion.andSelf(bounds);
1830 if (!drawRegion.isEmpty()) {
1831 layersSortedByZ.add(layer);
1832 } else {
1833 // Clear out the HWC layer if this layer was
1834 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001835 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001836 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001837 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001838 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001839 // WM changes displayDevice->layerStack upon sleep/awake.
1840 // Here we make sure we delete the HWC layers even if
1841 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001842 hwcLayerDestroyed = layer->destroyHwcLayer(
1843 displayDevice->getHwcDisplayId());
1844 }
1845
1846 // If a layer is not going to get a release fence because
1847 // it is invisible, but it is also going to release its
1848 // old buffer, add it to the list of layers needing
1849 // fences.
1850 if (hwcLayerDestroyed) {
1851 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1852 mLayersWithQueuedFrames.cend(), layer);
1853 if (found != mLayersWithQueuedFrames.cend()) {
1854 layersNeedingFences.add(layer);
1855 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001856 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001857 });
1858 }
1859 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001860 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001861 displayDevice->undefinedRegion.set(bounds);
1862 displayDevice->undefinedRegion.subtractSelf(
1863 tr.transform(opaqueRegion));
1864 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001865 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001866 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001867}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001868
Romain Guy0147a172017-06-01 13:53:56 -07001869mat4 SurfaceFlinger::computeSaturationMatrix() const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001870 if (mGlobalSaturationFactor == 1.0f) {
Romain Guy0147a172017-06-01 13:53:56 -07001871 return mat4();
1872 }
1873
1874 // Rec.709 luma coefficients
1875 float3 luminance{0.213f, 0.715f, 0.072f};
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001876 luminance *= 1.0f - mGlobalSaturationFactor;
Romain Guy0147a172017-06-01 13:53:56 -07001877 return mat4(
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001878 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
1879 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
1880 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
Romain Guy0147a172017-06-01 13:53:56 -07001881 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1882 );
1883}
1884
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001885// Returns a dataspace that fits all visible layers. The returned dataspace
1886// can only be one of
1887//
1888// - Dataspace::V0_SRGB
1889// - Dataspace::DISPLAY_P3
1890// - Dataspace::V0_SCRGB_LINEAR
1891// TODO(b/73825729) Add BT2020 data space.
1892ui::Dataspace SurfaceFlinger::getBestDataspace(
1893 const sp<const DisplayDevice>& displayDevice) const {
1894 Dataspace bestDataspace = Dataspace::V0_SRGB;
1895 for (const auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1896 switch (layer->getDataSpace()) {
1897 case Dataspace::V0_SCRGB:
1898 case Dataspace::V0_SCRGB_LINEAR:
1899 // return immediately
1900 return Dataspace::V0_SCRGB_LINEAR;
1901 case Dataspace::BT2020_PQ:
1902 case Dataspace::BT2020_ITU_PQ:
1903 // Historically, HDR dataspaces are ignored by SurfaceFlinger. But
1904 // since SurfaceFlinger simulates HDR support now, it should honor
1905 // them unless there is also native support.
1906 if (!displayDevice->hasHdr10()) {
1907 return Dataspace::V0_SCRGB_LINEAR;
1908 }
1909 break;
1910 case Dataspace::DISPLAY_P3:
1911 bestDataspace = Dataspace::DISPLAY_P3;
1912 break;
1913 default:
1914 break;
1915 }
Romain Guy54f154a2017-10-24 21:40:32 +01001916 }
1917
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001918 return bestDataspace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001919}
1920
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001921// Pick the ColorMode / Dataspace for the display device.
1922// TODO(b/73825729) Add BT2020 color mode.
1923void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& displayDevice,
1924 ColorMode* outMode, Dataspace* outDataSpace) const {
1925 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1926 *outMode = ColorMode::NATIVE;
1927 *outDataSpace = Dataspace::UNKNOWN;
1928 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001929 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001930
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001931 switch (getBestDataspace(displayDevice)) {
1932 case Dataspace::DISPLAY_P3:
1933 case Dataspace::V0_SCRGB_LINEAR:
1934 *outMode = ColorMode::DISPLAY_P3;
1935 *outDataSpace = Dataspace::DISPLAY_P3;
1936 break;
1937 default:
1938 *outMode = ColorMode::SRGB;
1939 *outDataSpace = Dataspace::V0_SRGB;
1940 break;
1941 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001942}
1943
Mathias Agopiancd60f992012-08-16 16:28:27 -07001944void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001945 ATRACE_CALL();
1946 ALOGV("setUpHWComposer");
1947
Jesse Hall028dc8f2013-08-20 16:35:32 -07001948 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001949 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1950 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1951 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1952
1953 // If nothing has changed (!dirty), don't recompose.
1954 // If something changed, but we don't currently have any visible layers,
1955 // and didn't when we last did a composition, then skip it this time.
1956 // The second rule does two things:
1957 // - When all layers are removed from a display, we'll emit one black
1958 // frame, then nothing more until we get new layers.
1959 // - When a display is created with a private layer stack, we won't
1960 // emit any black frames until a layer is added to the layer stack.
1961 bool mustRecompose = dirty && !(empty && wasEmpty);
1962
1963 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1964 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1965 mustRecompose ? "doing" : "skipping",
1966 dirty ? "+" : "-",
1967 empty ? "+" : "-",
1968 wasEmpty ? "+" : "-");
1969
Dan Stoza71433162014-02-04 16:22:36 -08001970 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001971
1972 if (mustRecompose) {
1973 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1974 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001975 }
1976
Dan Stoza9e56aa02015-11-02 13:00:03 -08001977 // build the h/w work list
1978 if (CC_UNLIKELY(mGeometryInvalid)) {
1979 mGeometryInvalid = false;
1980 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1981 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1982 const auto hwcId = displayDevice->getHwcDisplayId();
1983 if (hwcId >= 0) {
1984 const Vector<sp<Layer>>& currentLayers(
1985 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001986 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001987 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001988 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07001989 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001990 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001991 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001992 }
1993 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001994
Robert Carrae060832016-11-28 10:51:00 -08001995 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001996 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001997 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001998 }
1999 }
2000 }
2001 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002002 }
Riley Andrews03414a12014-07-01 14:22:59 -07002003
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002004
Romain Guy0147a172017-06-01 13:53:56 -07002005 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002006
Dan Stoza9e56aa02015-11-02 13:00:03 -08002007 // Set the per-frame data
2008 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2009 auto& displayDevice = mDisplays[displayId];
2010 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002011
Dan Stoza9e56aa02015-11-02 13:00:03 -08002012 if (hwcId < 0) {
2013 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07002014 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002015 if (colorMatrix != mPreviousColorMatrix) {
Yiwei Zhang7c64f172018-03-07 14:52:28 -08002016 displayDevice->setColorTransform(colorMatrix);
David Sodman105b7dc2017-11-04 20:28:14 -07002017 status_t result = getBE().mHwc->setColorTransform(hwcId, colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002018 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
2019 "display %zd: %d", displayId, result);
2020 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002021 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002022 if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2023 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002024 !displayDevice->hasHdr10()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002025 layer->forceClientComposition(hwcId);
2026 }
2027
chaviwc9232ed2017-11-14 15:31:15 -08002028 if (layer->getForceClientComposition(hwcId)) {
2029 ALOGV("[%s] Requesting Client composition", layer->getName().string());
2030 layer->setCompositionType(hwcId, HWC2::Composition::Client);
2031 continue;
2032 }
2033
Dan Stoza9e56aa02015-11-02 13:00:03 -08002034 layer->setPerFrameData(displayDevice);
2035 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002036
2037 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002038 ColorMode colorMode;
2039 Dataspace dataSpace;
2040 pickColorMode(displayDevice, &colorMode, &dataSpace);
2041 setActiveColorModeInternal(displayDevice, colorMode, dataSpace);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002042 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002043 }
2044
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002045 mPreviousColorMatrix = colorMatrix;
2046
Dan Stoza9e56aa02015-11-02 13:00:03 -08002047 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002048 auto& displayDevice = mDisplays[displayId];
2049 if (!displayDevice->isDisplayOn()) {
2050 continue;
2051 }
2052
David Sodman105b7dc2017-11-04 20:28:14 -07002053 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002054 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2055 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002056 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002057}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002058
Mathias Agopiancd60f992012-08-16 16:28:27 -07002059void SurfaceFlinger::doComposition() {
2060 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002061 ALOGV("doComposition");
2062
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002063 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002064 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002065 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002066 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002067 // transform the dirty region into this screen's coordinate space
2068 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002069
2070 // repaint the framebuffer (if needed)
2071 doDisplayComposition(hw, dirtyRegion);
2072
Mathias Agopiancd60f992012-08-16 16:28:27 -07002073 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002074 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002075 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002076 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002077 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002078}
2079
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002080void SurfaceFlinger::postFramebuffer()
2081{
Mathias Agopian841cde52012-03-01 15:44:37 -08002082 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002083 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002084
Mathias Agopiana44b0412011-10-16 18:46:35 -07002085 const nsecs_t now = systemTime();
2086 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002087
Dan Stoza9e56aa02015-11-02 13:00:03 -08002088 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2089 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002090 if (!displayDevice->isDisplayOn()) {
2091 continue;
2092 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002093 const auto hwcId = displayDevice->getHwcDisplayId();
2094 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002095 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002096 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002097 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002098 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002099 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002100 // The layer buffer from the previous frame (if any) is released
2101 // by HWC only when the release fence from this frame (if any) is
2102 // signaled. Always get the release fence from HWC first.
2103 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002104 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002105
2106 // If the layer was client composited in the previous frame, we
2107 // need to merge with the previous client target acquire fence.
2108 // Since we do not track that, always merge with the current
2109 // client target acquire fence when it is available, even though
2110 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002111 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002112 releaseFence = Fence::merge("LayerRelease", releaseFence,
2113 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002114 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002115
Dan Stoza9e56aa02015-11-02 13:00:03 -08002116 layer->onLayerDisplayed(releaseFence);
2117 }
Chia-I Wu83806892017-11-16 10:50:20 -08002118
2119 // We've got a list of layers needing fences, that are disjoint with
2120 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2121 // supply them with the present fence.
2122 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002123 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002124 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2125 layer->onLayerDisplayed(presentFence);
2126 }
2127 }
2128
Dan Stoza9e56aa02015-11-02 13:00:03 -08002129 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002130 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002131 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002132 }
2133
Mathias Agopiana44b0412011-10-16 18:46:35 -07002134 mLastSwapBufferTime = systemTime() - now;
2135 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002136
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002137 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002138 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2139 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2140 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2141 logFrameStats();
2142 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002143 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002144}
2145
Mathias Agopian87baae12012-07-31 12:38:26 -07002146void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002147{
Mathias Agopian841cde52012-03-01 15:44:37 -08002148 ATRACE_CALL();
2149
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002150 // here we keep a copy of the drawing state (that is the state that's
2151 // going to be overwritten by handleTransactionLocked()) outside of
2152 // mStateLock so that the side-effects of the State assignment
2153 // don't happen with mStateLock held (which can cause deadlocks).
2154 State drawingState(mDrawingState);
2155
Mathias Agopianca4d3602011-05-19 15:38:14 -07002156 Mutex::Autolock _l(mStateLock);
2157 const nsecs_t now = systemTime();
2158 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002159
Mathias Agopianca4d3602011-05-19 15:38:14 -07002160 // Here we're guaranteed that some transaction flags are set
2161 // so we can call handleTransactionLocked() unconditionally.
2162 // We call getTransactionFlags(), which will also clear the flags,
2163 // with mStateLock held to guarantee that mCurrentState won't change
2164 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002165
Dan Stoza2713c302018-03-28 17:07:36 -07002166 mVsyncModulator.setTransactionStart(VSyncModulator::TransactionStart::NORMAL);
Mathias Agopiane57f2922012-08-09 16:29:12 -07002167 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002168 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002169
Mathias Agopianca4d3602011-05-19 15:38:14 -07002170 mLastTransactionTime = systemTime() - now;
2171 mDebugInTransaction = 0;
2172 invalidateHwcGeometry();
2173 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002174}
2175
Lloyd Pique715a2c12017-12-14 17:18:08 -08002176DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique09594832018-01-22 17:48:03 -08002177 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002178 // Figure out whether the event is for the primary display or an
2179 // external display by matching the Hwc display id against one for a
2180 // connected display. If we did not find a match, we then check what
2181 // displays are not already connected to determine the type. If we don't
2182 // have a connected primary display, we assume the new display is meant to
2183 // be the primary display, and then if we don't have an external display,
2184 // we assume it is that.
2185 const auto primaryDisplayId =
2186 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2187 const auto externalDisplayId =
2188 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2189 if (primaryDisplayId && primaryDisplayId == display) {
2190 return DisplayDevice::DISPLAY_PRIMARY;
2191 } else if (externalDisplayId && externalDisplayId == display) {
2192 return DisplayDevice::DISPLAY_EXTERNAL;
2193 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2194 return DisplayDevice::DISPLAY_PRIMARY;
2195 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2196 return DisplayDevice::DISPLAY_EXTERNAL;
2197 }
2198
2199 return DisplayDevice::DISPLAY_ID_INVALID;
2200}
2201
Lloyd Piqueba04e622017-12-14 17:11:26 -08002202void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2203 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002204 auto displayType = determineDisplayType(event.display, event.connection);
2205 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2206 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2207 continue;
2208 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002209
2210 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2211 ALOGE("External displays are not supported by the vr hardware composer.");
2212 continue;
2213 }
2214
Lloyd Pique715a2c12017-12-14 17:18:08 -08002215 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002216
2217 if (event.connection == HWC2::Connection::Connected) {
Steven Thomas3bed0522018-03-20 15:40:48 -07002218 if (!mBuiltinDisplays[displayType].get()) {
2219 ALOGV("Creating built in display %d", displayType);
2220 mBuiltinDisplays[displayType] = new BBinder();
2221 // All non-virtual displays are currently considered secure.
2222 DisplayDeviceState info(displayType, true);
2223 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2224 "Built-in Screen" : "External Screen";
2225 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
Lloyd Pique4d234852018-01-22 17:21:36 -08002226 mInterceptor->saveDisplayCreation(info);
Steven Thomas3bed0522018-03-20 15:40:48 -07002227 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002228 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002229 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002230
Lloyd Piquefcd86612017-12-14 17:15:36 -08002231 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2232 if (idx >= 0) {
2233 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Lloyd Pique4d234852018-01-22 17:21:36 -08002234 mInterceptor->saveDisplayDeletion(info.displayId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002235 mCurrentState.displays.removeItemsAt(idx);
2236 }
2237 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002238 }
2239
2240 processDisplayChangesLocked();
2241 }
2242
2243 mPendingHotplugEvents.clear();
2244}
2245
Lloyd Pique09594832018-01-22 17:48:03 -08002246sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2247 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2248 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002249 bool hasWideColorGamut = false;
Lloyd Pique09594832018-01-22 17:48:03 -08002250 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002251 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Lloyd Pique09594832018-01-22 17:48:03 -08002252 for (ColorMode colorMode : modes) {
2253 switch (colorMode) {
2254 case ColorMode::DISPLAY_P3:
2255 case ColorMode::ADOBE_RGB:
2256 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002257 hasWideColorGamut = true;
Lloyd Pique09594832018-01-22 17:48:03 -08002258 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002259 // TODO(lpy) Handle BT2020, BT2100_PQ and BT2100_HLG properly.
Lloyd Pique09594832018-01-22 17:48:03 -08002260 default:
2261 break;
2262 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002263
2264 std::vector<RenderIntent> renderIntents = getHwComposer().getRenderIntents(hwcId,
2265 colorMode);
2266 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2267 for (auto intent : renderIntents) {
2268 if (intent == RenderIntent::ENHANCE) {
2269 mBuiltinDisplaySupportsEnhance = true;
2270 break;
2271 }
2272 }
2273 }
Lloyd Pique09594832018-01-22 17:48:03 -08002274 }
2275 }
2276
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002277 bool hasHdr10 = false;
2278 std::unique_ptr<HdrCapabilities> hdrCapabilities = getHwComposer().getHdrCapabilities(hwcId);
Lloyd Pique09594832018-01-22 17:48:03 -08002279 if (hdrCapabilities) {
2280 const std::vector<int32_t> types = hdrCapabilities->getSupportedHdrTypes();
2281 auto iter = std::find(types.cbegin(), types.cend(), HAL_HDR_HDR10);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002282 hasHdr10 = iter != types.cend();
Lloyd Pique09594832018-01-22 17:48:03 -08002283 }
2284
2285 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2286 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2287
2288 /*
2289 * Create our display's surface
2290 */
2291 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2292 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
2293 renderSurface->setAsync(state.type >= DisplayDevice::DISPLAY_VIRTUAL);
2294 renderSurface->setNativeWindow(nativeWindow.get());
2295 const int displayWidth = renderSurface->queryWidth();
2296 const int displayHeight = renderSurface->queryHeight();
2297
2298 // Make sure that composition can never be stalled by a virtual display
2299 // consumer that isn't processing buffers fast enough. We have to do this
2300 // in two places:
2301 // * Here, in case the display is composed entirely by HWC.
2302 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2303 // window's swap interval in eglMakeCurrent, so they'll override the
2304 // interval we set here.
2305 if (state.type >= DisplayDevice::DISPLAY_VIRTUAL) {
2306 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2307 }
2308
2309 // virtual displays are always considered enabled
2310 auto initialPowerMode = (state.type >= DisplayDevice::DISPLAY_VIRTUAL) ? HWC_POWER_MODE_NORMAL
2311 : HWC_POWER_MODE_OFF;
2312
2313 sp<DisplayDevice> hw =
2314 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2315 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002316 hasWideColorGamut, hasHdr10, initialPowerMode);
Lloyd Pique09594832018-01-22 17:48:03 -08002317
2318 if (maxFrameBufferAcquiredBuffers >= 3) {
2319 nativeWindowSurface->preallocateBuffers();
2320 }
2321
2322 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002323 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2324 if (hasWideColorGamut) {
Lloyd Pique09594832018-01-22 17:48:03 -08002325 defaultColorMode = ColorMode::SRGB;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002326 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique09594832018-01-22 17:48:03 -08002327 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002328 setActiveColorModeInternal(hw, defaultColorMode, defaultDataSpace);
Lloyd Pique09594832018-01-22 17:48:03 -08002329 hw->setLayerStack(state.layerStack);
2330 hw->setProjection(state.orientation, state.viewport, state.frame);
2331 hw->setDisplayName(state.displayName);
2332
2333 return hw;
2334}
2335
Lloyd Pique347200f2017-12-14 17:00:15 -08002336void SurfaceFlinger::processDisplayChangesLocked() {
2337 // here we take advantage of Vector's copy-on-write semantics to
2338 // improve performance by skipping the transaction entirely when
2339 // know that the lists are identical
2340 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2341 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2342 if (!curr.isIdenticalTo(draw)) {
2343 mVisibleRegionsDirty = true;
2344 const size_t cc = curr.size();
2345 size_t dc = draw.size();
2346
2347 // find the displays that were removed
2348 // (ie: in drawing state but not in current state)
2349 // also handle displays that changed
2350 // (ie: displays that are in both lists)
2351 for (size_t i = 0; i < dc;) {
2352 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2353 if (j < 0) {
2354 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002355 // Call makeCurrent() on the primary display so we can
2356 // be sure that nothing associated with this display
2357 // is current.
2358 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2359 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2360 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2361 if (hw != nullptr) hw->disconnect(getHwComposer());
2362 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2363 mEventThread->onHotplugReceived(draw[i].type, false);
2364 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002365 } else {
2366 // this display is in both lists. see if something changed.
2367 const DisplayDeviceState& state(curr[j]);
2368 const wp<IBinder>& display(curr.keyAt(j));
2369 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2370 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2371 if (state_binder != draw_binder) {
2372 // changing the surface is like destroying and
2373 // recreating the DisplayDevice, so we just remove it
2374 // from the drawing state, so that it get re-added
2375 // below.
2376 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2377 if (hw != nullptr) hw->disconnect(getHwComposer());
2378 mDisplays.removeItem(display);
2379 mDrawingState.displays.removeItemsAt(i);
2380 dc--;
2381 // at this point we must loop to the next item
2382 continue;
2383 }
2384
2385 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2386 if (disp != nullptr) {
2387 if (state.layerStack != draw[i].layerStack) {
2388 disp->setLayerStack(state.layerStack);
2389 }
2390 if ((state.orientation != draw[i].orientation) ||
2391 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2392 disp->setProjection(state.orientation, state.viewport, state.frame);
2393 }
2394 if (state.width != draw[i].width || state.height != draw[i].height) {
2395 disp->setDisplaySize(state.width, state.height);
2396 }
2397 }
2398 }
2399 ++i;
2400 }
2401
2402 // find displays that were added
2403 // (ie: in current state but not in drawing state)
2404 for (size_t i = 0; i < cc; i++) {
2405 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2406 const DisplayDeviceState& state(curr[i]);
2407
2408 sp<DisplaySurface> dispSurface;
2409 sp<IGraphicBufferProducer> producer;
2410 sp<IGraphicBufferProducer> bqProducer;
2411 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002412 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002413
2414 int32_t hwcId = -1;
2415 if (state.isVirtualDisplay()) {
2416 // Virtual displays without a surface are dormant:
2417 // they have external state (layer stack, projection,
2418 // etc.) but no internal state (i.e. a DisplayDevice).
2419 if (state.surface != nullptr) {
2420 // Allow VR composer to use virtual displays.
2421 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2422 int width = 0;
2423 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2424 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2425 int height = 0;
2426 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2427 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2428 int intFormat = 0;
2429 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2430 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002431 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002432
2433 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2434 }
2435
2436 // TODO: Plumb requested format back up to consumer
2437
2438 sp<VirtualDisplaySurface> vds =
2439 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2440 bqProducer, bqConsumer,
2441 state.displayName);
2442
2443 dispSurface = vds;
2444 producer = vds;
2445 }
2446 } else {
2447 ALOGE_IF(state.surface != nullptr,
2448 "adding a supported display, but rendering "
2449 "surface is provided (%p), ignoring it",
2450 state.surface.get());
2451
2452 hwcId = state.type;
2453 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2454 producer = bqProducer;
2455 }
2456
2457 const wp<IBinder>& display(curr.keyAt(i));
2458 if (dispSurface != nullptr) {
Lloyd Pique09594832018-01-22 17:48:03 -08002459 mDisplays.add(display,
2460 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2461 producer));
Lloyd Pique347200f2017-12-14 17:00:15 -08002462 if (!state.isVirtualDisplay()) {
2463 mEventThread->onHotplugReceived(state.type, true);
2464 }
2465 }
2466 }
2467 }
2468 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002469
2470 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002471}
2472
Mathias Agopian87baae12012-07-31 12:38:26 -07002473void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002474{
Dan Stoza7dde5992015-05-22 09:51:44 -07002475 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002476 mCurrentState.traverseInZOrder([](Layer* layer) {
2477 layer->notifyAvailableFrames();
2478 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002479
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002480 /*
2481 * Traversal of the children
2482 * (perform the transaction for each of them if needed)
2483 */
2484
Mathias Agopian3559b072012-08-15 13:46:03 -07002485 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002486 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002487 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002488 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002489
2490 const uint32_t flags = layer->doTransaction(0);
2491 if (flags & Layer::eVisibleRegion)
2492 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002493 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002494 }
2495
2496 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002497 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002498 */
2499
Mathias Agopiane57f2922012-08-09 16:29:12 -07002500 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002501 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002502 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002503 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002504
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002505 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002506 // The transform hint might have changed for some layers
2507 // (either because a display has changed, or because a layer
2508 // as changed).
2509 //
2510 // Walk through all the layers in currentLayers,
2511 // and update their transform hint.
2512 //
2513 // If a layer is visible only on a single display, then that
2514 // display is used to calculate the hint, otherwise we use the
2515 // default display.
2516 //
2517 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2518 // the hint is set before we acquire a buffer from the surface texture.
2519 //
2520 // NOTE: layer transactions have taken place already, so we use their
2521 // drawing state. However, SurfaceFlinger's own transaction has not
2522 // happened yet, so we must use the current state layer list
2523 // (soon to become the drawing state list).
2524 //
2525 sp<const DisplayDevice> disp;
2526 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002527 bool first = true;
2528 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002529 // NOTE: we rely on the fact that layers are sorted by
2530 // layerStack first (so we don't have to traverse the list
2531 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002532 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002533 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002534 currentlayerStack = layerStack;
2535 // figure out if this layerstack is mirrored
2536 // (more than one display) if so, pick the default display,
2537 // if not, pick the only display it's on.
2538 disp.clear();
2539 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2540 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002541 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002542 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002543 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002544 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002545 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002546 break;
2547 }
2548 }
2549 }
2550 }
Chet Haase91d25932013-04-11 15:24:55 -07002551
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002552 if (disp == nullptr) {
2553 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2554 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002555
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002556 // could be null when this layer is using a layerStack
2557 // that is not visible on any display. Also can occur at
2558 // screen off/on times.
2559 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002560 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002561
2562 // disp can be null if there is no display available at all to get
2563 // the transform hint from.
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002564 if (disp != nullptr) {
2565 layer->updateTransformHint(disp);
2566 }
Robert Carr2047fae2016-11-28 14:09:09 -08002567
2568 first = false;
2569 });
Mathias Agopian84300952012-11-21 16:02:13 -08002570 }
2571
2572
Mathias Agopian3559b072012-08-15 13:46:03 -07002573 /*
2574 * Perform our own transaction if needed
2575 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002576
2577 if (mLayersAdded) {
2578 mLayersAdded = false;
2579 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002580 mVisibleRegionsDirty = true;
2581 }
2582
2583 // some layers might have been removed, so
2584 // we need to update the regions they're exposing.
2585 if (mLayersRemoved) {
2586 mLayersRemoved = false;
2587 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002588 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002589 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002590 // this layer is not visible anymore
2591 // TODO: we could traverse the tree from front to back and
2592 // compute the actual visible region
2593 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002594 Region visibleReg;
2595 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002596 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002597 }
Robert Carr2047fae2016-11-28 14:09:09 -08002598 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002599 }
2600
2601 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002602
2603 updateCursorAsync();
2604}
2605
2606void SurfaceFlinger::updateCursorAsync()
2607{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002608 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2609 auto& displayDevice = mDisplays[displayId];
2610 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002611 continue;
2612 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002613
2614 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2615 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002616 }
2617 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002618}
2619
2620void SurfaceFlinger::commitTransaction()
2621{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002622 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002623 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002624 for (const auto& l : mLayersPendingRemoval) {
2625 recordBufferingStats(l->getName().string(),
2626 l->getOccupancyHistory(true));
2627 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002628 }
2629 mLayersPendingRemoval.clear();
2630 }
2631
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002632 // If this transaction is part of a window animation then the next frame
2633 // we composite should be considered an animation as well.
2634 mAnimCompositionPending = mAnimTransactionPending;
2635
Mathias Agopian4fec8732012-06-29 14:12:52 -07002636 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002637 mDrawingState.traverseInZOrder([](Layer* layer) {
2638 layer->commitChildList();
2639 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002640 mTransactionPending = false;
2641 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002642 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002643}
2644
Chia-I Wuab0c3192017-08-01 11:29:00 -07002645void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002646 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002647{
Mathias Agopian841cde52012-03-01 15:44:37 -08002648 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002649 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002650
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002651 Region aboveOpaqueLayers;
2652 Region aboveCoveredLayers;
2653 Region dirty;
2654
Mathias Agopian87baae12012-07-31 12:38:26 -07002655 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002656
Robert Carr2047fae2016-11-28 14:09:09 -08002657 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002658 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002659 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002660
Jesse Hall01e29052013-02-19 16:13:35 -08002661 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002662 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002663 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002664
Mathias Agopianab028732010-03-16 16:41:46 -07002665 /*
2666 * opaqueRegion: area of a surface that is fully opaque.
2667 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002668 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002669
2670 /*
2671 * visibleRegion: area of a surface that is visible on screen
2672 * and not fully transparent. This is essentially the layer's
2673 * footprint minus the opaque regions above it.
2674 * Areas covered by a translucent surface are considered visible.
2675 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002676 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002677
2678 /*
2679 * coveredRegion: area of a surface that is covered by all
2680 * visible regions above it (which includes the translucent areas).
2681 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002682 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002683
Jesse Halla8026d22012-09-25 13:25:04 -07002684 /*
2685 * transparentRegion: area of a surface that is hinted to be completely
2686 * transparent. This is only used to tell when the layer has no visible
2687 * non-transparent regions and can be removed from the layer list. It
2688 * does not affect the visibleRegion of this layer or any layers
2689 * beneath it. The hint may not be correct if apps don't respect the
2690 * SurfaceView restrictions (which, sadly, some don't).
2691 */
2692 Region transparentRegion;
2693
Mathias Agopianab028732010-03-16 16:41:46 -07002694
2695 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002696 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002697 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002698 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002699 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002700 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002701 if (!visibleRegion.isEmpty()) {
2702 // Remove the transparent area from the visible region
2703 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002704 if (tr.preserveRects()) {
2705 // transform the transparent region
2706 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002707 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002708 // transformation too complex, can't do the
2709 // transparent region optimization.
2710 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002711 }
Mathias Agopianab028732010-03-16 16:41:46 -07002712 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002713
Mathias Agopianab028732010-03-16 16:41:46 -07002714 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002715 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002716 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002717 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2718 // the opaque region is the layer's footprint
2719 opaqueRegion = visibleRegion;
2720 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002721 }
2722 }
2723
Robert Carre5f4f692018-01-12 13:12:28 -08002724 if (visibleRegion.isEmpty()) {
2725 layer->clearVisibilityRegions();
2726 return;
2727 }
2728
Mathias Agopianab028732010-03-16 16:41:46 -07002729 // Clip the covered region to the visible region
2730 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2731
2732 // Update aboveCoveredLayers for next (lower) layer
2733 aboveCoveredLayers.orSelf(visibleRegion);
2734
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002735 // subtract the opaque region covered by the layers above us
2736 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002737
2738 // compute this layer's dirty region
2739 if (layer->contentDirty) {
2740 // we need to invalidate the whole region
2741 dirty = visibleRegion;
2742 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002743 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002744 layer->contentDirty = false;
2745 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002746 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002747 * the exposed region consists of two components:
2748 * 1) what's VISIBLE now and was COVERED before
2749 * 2) what's EXPOSED now less what was EXPOSED before
2750 *
2751 * note that (1) is conservative, we start with the whole
2752 * visible region but only keep what used to be covered by
2753 * something -- which mean it may have been exposed.
2754 *
2755 * (2) handles areas that were not covered by anything but got
2756 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002757 */
Mathias Agopianab028732010-03-16 16:41:46 -07002758 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002759 const Region oldVisibleRegion = layer->visibleRegion;
2760 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002761 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2762 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002763 }
2764 dirty.subtractSelf(aboveOpaqueLayers);
2765
2766 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002767 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002768
Mathias Agopianab028732010-03-16 16:41:46 -07002769 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002770 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002771
Jesse Halla8026d22012-09-25 13:25:04 -07002772 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002773 layer->setVisibleRegion(visibleRegion);
2774 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002775 layer->setVisibleNonTransparentRegion(
2776 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002777 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002778
Mathias Agopian87baae12012-07-31 12:38:26 -07002779 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002780}
2781
Chia-I Wuab0c3192017-08-01 11:29:00 -07002782void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002783 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002784 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002785 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002786 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002787 }
2788 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002789}
2790
Dan Stoza6b9454d2014-11-07 16:00:59 -08002791bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002792{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002793 ALOGV("handlePageFlip");
2794
Brian Andersond6927fb2016-07-23 23:37:30 -07002795 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002796
Mathias Agopian4fec8732012-06-29 14:12:52 -07002797 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002798 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002799 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002800
2801 // Store the set of layers that need updates. This set must not change as
2802 // buffers are being latched, as this could result in a deadlock.
2803 // Example: Two producers share the same command stream and:
2804 // 1.) Layer 0 is latched
2805 // 2.) Layer 0 gets a new frame
2806 // 2.) Layer 1 gets a new frame
2807 // 3.) Layer 1 is latched.
2808 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2809 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002810 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002811 if (layer->hasQueuedFrame()) {
2812 frameQueued = true;
2813 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002814 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002815 } else {
2816 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002817 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002818 } else {
2819 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002820 }
Robert Carr2047fae2016-11-28 14:09:09 -08002821 });
2822
Dan Stoza9e56aa02015-11-02 13:00:03 -08002823 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002824 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002825 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002826 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002827 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002828 newDataLatched = true;
2829 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002830 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002831
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002832 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002833
2834 // If we will need to wake up at some time in the future to deal with a
2835 // queued frame that shouldn't be displayed during this vsync period, wake
2836 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002837 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002838 signalLayerUpdate();
2839 }
2840
2841 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002842 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002843}
2844
Mathias Agopianad456f92011-01-13 17:53:01 -08002845void SurfaceFlinger::invalidateHwcGeometry()
2846{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002847 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002848}
2849
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002850
Fabien Sanglard830b8472016-11-30 16:35:58 -08002851void SurfaceFlinger::doDisplayComposition(
2852 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002853 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002854{
Dan Stoza71433162014-02-04 16:22:36 -08002855 // We only need to actually compose the display if:
2856 // 1) It is being handled by hardware composer, which may need this to
2857 // keep its virtual display state machine in sync, or
2858 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002859 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002860 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002861 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002862 return;
2863 }
2864
Dan Stoza9e56aa02015-11-02 13:00:03 -08002865 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002866 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002867
2868 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002869 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002870}
2871
Chia-I Wub02087d2017-11-09 10:19:54 -08002872bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002873{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002874 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002875
Chia-I Wub02087d2017-11-09 10:19:54 -08002876 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002877 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002878 const auto hwcId = displayDevice->getHwcDisplayId();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002879 const bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
2880 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
2881 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2882 HWC2::Capability::SkipClientColorTransform);
2883 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002884
2885 mat4 oldColorMatrix;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002886 mat4 legacySrgbSaturationMatrix = mLegacySrgbSaturationMatrix;
2887 const bool applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002888 if (applyColorMatrix) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002889 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002890 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002891 legacySrgbSaturationMatrix = colorMatrix * legacySrgbSaturationMatrix;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002892 }
2893
Dan Stoza9e56aa02015-11-02 13:00:03 -08002894 if (hasClientComposition) {
2895 ALOGV("hasClientComposition");
2896
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002897 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002898 if (displayDevice->hasWideColorGamut()) {
2899 outputDataspace = displayDevice->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002900 }
2901 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
2902
Chia-I Wu7f402902017-11-09 12:51:10 -08002903 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002904 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002905 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002906 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002907
2908 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002909 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002910 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2911 }
2912 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002913 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002914
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002915 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002916 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002917 // when using overlays, we assume a fully transparent framebuffer
2918 // NOTE: we could reduce how much we need to clear, for instance
2919 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002920 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002921 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002922 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002923 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002924 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002925 // we're left with the letterbox region
2926 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002927 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002928
2929 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002930 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002931
Mathias Agopianb9494d52012-04-18 02:28:45 -07002932 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002933 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002934 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002935 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002936 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002937 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002938
Dan Stoza9e56aa02015-11-02 13:00:03 -08002939 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002940 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002941 // scissor on the main display. It should never be needed
2942 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002943 const Rect& bounds(displayDevice->getBounds());
2944 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002945 if (scissor != bounds) {
2946 // scissor doesn't match the screen's dimensions, so we
2947 // need to clear everything outside of it and enable
2948 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002949
Mathias Agopianf45c5102012-10-24 16:29:17 -07002950 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002951 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002952 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002953 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002954 }
2955 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002956 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002957
Mathias Agopian85d751c2012-08-29 16:59:24 -07002958 /*
2959 * and then, render the layers targeted at the framebuffer
2960 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002961
Dan Stoza9e56aa02015-11-02 13:00:03 -08002962 ALOGV("Rendering client layers");
2963 const Transform& displayTransform = displayDevice->getTransform();
2964 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002965 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002966 bool firstLayer = true;
2967 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002968 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002969 displayTransform.transform(layer->visibleRegion)));
2970 ALOGV("Layer: %s", layer->getName().string());
2971 ALOGV(" Composition type: %s",
2972 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002973 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002974 switch (layer->getCompositionType(hwcId)) {
2975 case HWC2::Composition::Cursor:
2976 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002977 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002978 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002979 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002980 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002981 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002982 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002983 // never clear the very first layer since we're
2984 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002985 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002986 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002987 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002988 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002989 case HWC2::Composition::Client: {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002990 // Only apply saturation matrix layer that is legacy SRGB dataspace
2991 // when auto color mode is on.
2992 bool restore = false;
2993 mat4 savedMatrix;
2994 if (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
2995 layer->isLegacySrgbDataSpace()) {
2996 savedMatrix =
2997 getRenderEngine().setupColorTransform(legacySrgbSaturationMatrix);
2998 restore = true;
2999 }
chaviwa76b2712017-09-20 12:02:26 -07003000 layer->draw(renderArea, clip);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003001 if (restore) {
3002 getRenderEngine().setupColorTransform(savedMatrix);
3003 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003004 break;
3005 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003006 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07003007 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003008 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003009 } else {
3010 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003011 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003012 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003013 }
3014 } else {
3015 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08003016 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08003017 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08003018 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07003019 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07003020 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07003021 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003022 }
3023 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003024
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003025 if (applyColorMatrix) {
3026 getRenderEngine().setupColorTransform(oldColorMatrix);
3027 }
3028
Mathias Agopianf45c5102012-10-24 16:29:17 -07003029 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003030 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003031 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003032}
3033
Fabien Sanglard830b8472016-11-30 16:35:58 -08003034void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
3035 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003036 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003037 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003038}
3039
Dan Stoza7d89d062015-04-30 13:29:25 -07003040status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003041 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003042 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003043 const sp<Layer>& lbc,
3044 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003045{
Dan Stoza7d89d062015-04-30 13:29:25 -07003046 // add this layer to the current state list
3047 {
3048 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003049 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003050 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3051 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003052 return NO_MEMORY;
3053 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003054 if (parent == nullptr) {
3055 mCurrentState.layersSortedByZ.add(lbc);
3056 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003057 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003058 ALOGE("addClientLayer called with a removed parent");
3059 return NAME_NOT_FOUND;
3060 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003061 parent->addChild(lbc);
3062 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003063
Dan Stoza101d8dc2018-02-27 15:42:25 -08003064 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
Dan Stoza0a0158c2018-03-16 13:38:54 -07003065 // TODO (b/74616334): Change this back to a fatal assert once the leak is fixed
3066 ALOGE_IF(mGraphicBufferProducerList.size() > mMaxGraphicBufferProducerListSize,
3067 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3068 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize,
3069 mNumLayers);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003070 mLayersAdded = true;
3071 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003072 }
3073
Mathias Agopian96f08192010-06-02 23:28:45 -07003074 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003075 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003076
Dan Stoza7d89d062015-04-30 13:29:25 -07003077 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003078}
3079
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003080status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003081 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003082 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3083}
Robert Carr7f9b8992017-03-10 11:08:39 -08003084
chaviwca27f252018-02-06 16:46:39 -08003085status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3086 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003087 if (layer->isPendingRemoval()) {
3088 return NO_ERROR;
3089 }
3090
Robert Carr1f0a16a2016-10-24 16:27:39 -07003091 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003092 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003093 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003094 if (topLevelOnly) {
3095 return NO_ERROR;
3096 }
3097
Chia-I Wu98f1c102017-05-30 14:54:08 -07003098 sp<Layer> ancestor = p;
3099 while (ancestor->getParent() != nullptr) {
3100 ancestor = ancestor->getParent();
3101 }
3102 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3103 ALOGE("removeLayer called with a layer whose parent has been removed");
3104 return NAME_NOT_FOUND;
3105 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003106
3107 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003108 } else {
3109 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003110 }
3111
Robert Carr136e2f62017-02-08 17:54:29 -08003112 // As a matter of normal operation, the LayerCleaner will produce a second
3113 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3114 // so we will succeed in promoting it, but it's already been removed
3115 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3116 // otherwise something has gone wrong and we are leaking the layer.
3117 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003118 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3119 layer->getName().string(),
3120 (p != nullptr) ? p->getName().string() : "no-parent");
3121 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003122 } else if (index < 0) {
3123 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003124 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003125
Chia-I Wuc6657022017-08-15 11:18:17 -07003126 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003127 mLayersPendingRemoval.add(layer);
3128 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003129 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003130 setTransactionFlags(eTransactionNeeded);
3131 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003132}
3133
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003134uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003135 return android_atomic_release_load(&mTransactionFlags);
3136}
3137
Mathias Agopian3f844832013-08-07 21:24:32 -07003138uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003139 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3140}
3141
Mathias Agopian3f844832013-08-07 21:24:32 -07003142uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza2713c302018-03-28 17:07:36 -07003143 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3144}
3145
3146uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3147 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003148 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza2713c302018-03-28 17:07:36 -07003149 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003150 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003151 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003152 }
3153 return old;
3154}
3155
chaviwca27f252018-02-06 16:46:39 -08003156bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3157 for (const ComposerState& state : states) {
3158 // Here we need to check that the interface we're given is indeed
3159 // one of our own. A malicious client could give us a nullptr
3160 // IInterface, or one of its own or even one of our own but a
3161 // different type. All these situations would cause us to crash.
3162 if (state.client == nullptr) {
3163 return true;
3164 }
3165
3166 sp<IBinder> binder = IInterface::asBinder(state.client);
3167 if (binder == nullptr) {
3168 return true;
3169 }
3170
3171 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3172 return true;
3173 }
3174 }
3175 return false;
3176}
3177
Mathias Agopian8b33f032012-07-24 20:43:54 -07003178void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003179 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003180 const Vector<DisplayState>& displays,
3181 uint32_t flags)
3182{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003183 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003184 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003185 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003186
chaviwca27f252018-02-06 16:46:39 -08003187 if (containsAnyInvalidClientState(states)) {
3188 return;
3189 }
3190
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003191 if (flags & eAnimation) {
3192 // For window updates that are part of an animation we must wait for
3193 // previous animation "frames" to be handled.
3194 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003195 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003196 if (CC_UNLIKELY(err != NO_ERROR)) {
3197 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003198 // caller after a few seconds.
3199 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3200 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003201 mAnimTransactionPending = false;
3202 break;
3203 }
3204 }
3205 }
3206
chaviwca27f252018-02-06 16:46:39 -08003207 for (const DisplayState& display : displays) {
3208 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003209 }
3210
chaviwca27f252018-02-06 16:46:39 -08003211 for (const ComposerState& state : states) {
3212 transactionFlags |= setClientStateLocked(state);
3213 }
3214
3215 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3216 // as destroyed should only occur after setting all other states. This is to allow for a
3217 // child re-parent to happen before marking its original parent as destroyed (which would
3218 // then mark the child as destroyed).
3219 for (const ComposerState& state : states) {
3220 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003221 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003222
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003223 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3224 // anyway. This can be used as a flush mechanism for previous async transactions.
3225 // Empty animation transaction can be used to simulate back-pressure, so also force a
3226 // transaction for empty animation transactions.
3227 if (transactionFlags == 0 &&
3228 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003229 transactionFlags = eTransactionNeeded;
3230 }
3231
Mathias Agopian386aa982011-11-07 21:58:03 -08003232 if (transactionFlags) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003233 if (mInterceptor->isEnabled()) {
3234 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003235 }
Irvel468051e2016-06-13 16:44:44 -07003236
Mathias Agopian386aa982011-11-07 21:58:03 -08003237 // this triggers the transaction
Dan Stoza2713c302018-03-28 17:07:36 -07003238 const auto start = (flags & eEarlyWakeup)
3239 ? VSyncModulator::TransactionStart::EARLY
3240 : VSyncModulator::TransactionStart::NORMAL;
3241 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003242
3243 // if this is a synchronous transaction, wait for it to take effect
3244 // before returning.
3245 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003246 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003247 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003248 if (flags & eAnimation) {
3249 mAnimTransactionPending = true;
3250 }
3251 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003252 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3253 if (CC_UNLIKELY(err != NO_ERROR)) {
3254 // just in case something goes wrong in SF, return to the
3255 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003256 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3257 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003258 break;
3259 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003260 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003261 }
3262}
3263
Mathias Agopiane57f2922012-08-09 16:29:12 -07003264uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3265{
Jesse Hall9a143922012-10-04 16:29:19 -07003266 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3267 if (dpyIdx < 0)
3268 return 0;
3269
Mathias Agopiane57f2922012-08-09 16:29:12 -07003270 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003271 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003272 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003273 const uint32_t what = s.what;
3274 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003275 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003276 disp.surface = s.surface;
3277 flags |= eDisplayTransactionNeeded;
3278 }
3279 }
3280 if (what & DisplayState::eLayerStackChanged) {
3281 if (disp.layerStack != s.layerStack) {
3282 disp.layerStack = s.layerStack;
3283 flags |= eDisplayTransactionNeeded;
3284 }
3285 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003286 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003287 if (disp.orientation != s.orientation) {
3288 disp.orientation = s.orientation;
3289 flags |= eDisplayTransactionNeeded;
3290 }
3291 if (disp.frame != s.frame) {
3292 disp.frame = s.frame;
3293 flags |= eDisplayTransactionNeeded;
3294 }
3295 if (disp.viewport != s.viewport) {
3296 disp.viewport = s.viewport;
3297 flags |= eDisplayTransactionNeeded;
3298 }
3299 }
Michael Lentine47e45402014-07-18 15:34:25 -07003300 if (what & DisplayState::eDisplaySizeChanged) {
3301 if (disp.width != s.width) {
3302 disp.width = s.width;
3303 flags |= eDisplayTransactionNeeded;
3304 }
3305 if (disp.height != s.height) {
3306 disp.height = s.height;
3307 flags |= eDisplayTransactionNeeded;
3308 }
3309 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003310 }
3311 return flags;
3312}
3313
chaviwca27f252018-02-06 16:46:39 -08003314uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3315 const layer_state_t& s = composerState.state;
3316 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3317
Mathias Agopian13127d82013-03-05 17:47:11 -08003318 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003319 if (layer == nullptr) {
3320 return 0;
3321 }
3322
3323 if (layer->isPendingRemoval()) {
3324 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3325 return 0;
3326 }
3327
3328 uint32_t flags = 0;
3329
3330 const uint32_t what = s.what;
3331 bool geometryAppliesWithResize =
3332 what & layer_state_t::eGeometryAppliesWithResize;
3333 if (what & layer_state_t::ePositionChanged) {
3334 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3335 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003336 }
chaviw8b3871a2017-11-01 17:41:01 -07003337 }
3338 if (what & layer_state_t::eLayerChanged) {
3339 // NOTE: index needs to be calculated before we update the state
3340 const auto& p = layer->getParent();
3341 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003342 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003343 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003344 mCurrentState.layersSortedByZ.removeAt(idx);
3345 mCurrentState.layersSortedByZ.add(layer);
3346 // we need traversal (state changed)
3347 // AND transaction (list changed)
3348 flags |= eTransactionNeeded|eTraversalNeeded;
3349 }
chaviw8b3871a2017-11-01 17:41:01 -07003350 } else {
3351 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003352 flags |= eTransactionNeeded|eTraversalNeeded;
3353 }
3354 }
chaviw8b3871a2017-11-01 17:41:01 -07003355 }
3356 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003357 // NOTE: index needs to be calculated before we update the state
3358 const auto& p = layer->getParent();
3359 if (p == nullptr) {
3360 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3361 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3362 mCurrentState.layersSortedByZ.removeAt(idx);
3363 mCurrentState.layersSortedByZ.add(layer);
3364 // we need traversal (state changed)
3365 // AND transaction (list changed)
3366 flags |= eTransactionNeeded|eTraversalNeeded;
3367 }
3368 } else {
3369 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3370 flags |= eTransactionNeeded|eTraversalNeeded;
3371 }
chaviw8b3871a2017-11-01 17:41:01 -07003372 }
3373 }
3374 if (what & layer_state_t::eSizeChanged) {
3375 if (layer->setSize(s.w, s.h)) {
3376 flags |= eTraversalNeeded;
3377 }
3378 }
3379 if (what & layer_state_t::eAlphaChanged) {
3380 if (layer->setAlpha(s.alpha))
3381 flags |= eTraversalNeeded;
3382 }
3383 if (what & layer_state_t::eColorChanged) {
3384 if (layer->setColor(s.color))
3385 flags |= eTraversalNeeded;
3386 }
3387 if (what & layer_state_t::eMatrixChanged) {
3388 if (layer->setMatrix(s.matrix))
3389 flags |= eTraversalNeeded;
3390 }
3391 if (what & layer_state_t::eTransparentRegionChanged) {
3392 if (layer->setTransparentRegionHint(s.transparentRegion))
3393 flags |= eTraversalNeeded;
3394 }
3395 if (what & layer_state_t::eFlagsChanged) {
3396 if (layer->setFlags(s.flags, s.mask))
3397 flags |= eTraversalNeeded;
3398 }
3399 if (what & layer_state_t::eCropChanged) {
3400 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3401 flags |= eTraversalNeeded;
3402 }
3403 if (what & layer_state_t::eFinalCropChanged) {
3404 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3405 flags |= eTraversalNeeded;
3406 }
3407 if (what & layer_state_t::eLayerStackChanged) {
3408 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3409 // We only allow setting layer stacks for top level layers,
3410 // everything else inherits layer stack from its parent.
3411 if (layer->hasParent()) {
3412 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3413 layer->getName().string());
3414 } else if (idx < 0) {
3415 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3416 "that also does not appear in the top level layer list. Something"
3417 " has gone wrong.", layer->getName().string());
3418 } else if (layer->setLayerStack(s.layerStack)) {
3419 mCurrentState.layersSortedByZ.removeAt(idx);
3420 mCurrentState.layersSortedByZ.add(layer);
3421 // we need traversal (state changed)
3422 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003423 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003424 }
3425 }
3426 if (what & layer_state_t::eDeferTransaction) {
3427 if (s.barrierHandle != nullptr) {
3428 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3429 } else if (s.barrierGbp != nullptr) {
3430 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3431 if (authenticateSurfaceTextureLocked(gbp)) {
3432 const auto& otherLayer =
3433 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3434 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3435 } else {
3436 ALOGE("Attempt to defer transaction to to an"
3437 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003438 }
3439 }
chaviw8b3871a2017-11-01 17:41:01 -07003440 // We don't trigger a traversal here because if no other state is
3441 // changed, we don't want this to cause any more work
3442 }
3443 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003444 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003445 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003446 if (!hadParent) {
3447 mCurrentState.layersSortedByZ.remove(layer);
3448 }
chaviw8b3871a2017-11-01 17:41:01 -07003449 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003450 }
chaviw8b3871a2017-11-01 17:41:01 -07003451 }
3452 if (what & layer_state_t::eReparentChildren) {
3453 if (layer->reparentChildren(s.reparentHandle)) {
3454 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003455 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003456 }
chaviw8b3871a2017-11-01 17:41:01 -07003457 if (what & layer_state_t::eDetachChildren) {
3458 layer->detachChildren();
3459 }
3460 if (what & layer_state_t::eOverrideScalingModeChanged) {
3461 layer->setOverrideScalingMode(s.overrideScalingMode);
3462 // We don't trigger a traversal here because if no other state is
3463 // changed, we don't want this to cause any more work
3464 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003465 return flags;
3466}
3467
chaviwca27f252018-02-06 16:46:39 -08003468void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3469 const layer_state_t& state = composerState.state;
3470 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3471
3472 sp<Layer> layer(client->getLayerUser(state.surface));
3473 if (layer == nullptr) {
3474 return;
3475 }
3476
3477 if (layer->isPendingRemoval()) {
3478 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3479 return;
3480 }
3481
3482 if (state.what & layer_state_t::eDestroySurface) {
3483 removeLayerLocked(mStateLock, layer);
3484 }
3485}
3486
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003487status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003488 const String8& name,
3489 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003490 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliuccd34842018-03-14 12:26:23 -07003491 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003492 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003493{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003494 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003495 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003496 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003497 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003498 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003499
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003500 status_t result = NO_ERROR;
3501
3502 sp<Layer> layer;
3503
Cody Northropbc755282017-03-31 12:00:08 -06003504 String8 uniqueName = getUniqueLayerName(name);
3505
Mathias Agopian3165cc22012-08-08 19:42:09 -07003506 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3507 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003508 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003509 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003510 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003511
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003512 break;
chaviw13fdc492017-06-27 12:40:18 -07003513 case ISurfaceComposerClient::eFXSurfaceColor:
3514 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003515 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003516 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003517 break;
3518 default:
3519 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003520 break;
3521 }
3522
Dan Stoza7d89d062015-04-30 13:29:25 -07003523 if (result != NO_ERROR) {
3524 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003525 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003526
Chia-I Wuab0c3192017-08-01 11:29:00 -07003527 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3528 // TODO b/64227542
3529 if (windowType == 441731) {
3530 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3531 layer->setPrimaryDisplayOnly();
3532 }
3533
Albert Chaulk479c60c2017-01-27 14:21:34 -05003534 layer->setInfo(windowType, ownerUid);
3535
Robert Carr1f0a16a2016-10-24 16:27:39 -07003536 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003537 if (result != NO_ERROR) {
3538 return result;
3539 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003540 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003541
3542 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003543 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003544}
3545
Cody Northropbc755282017-03-31 12:00:08 -06003546String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3547{
3548 bool matchFound = true;
3549 uint32_t dupeCounter = 0;
3550
3551 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3552 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3553
3554 // Loop over layers until we're sure there is no matching name
3555 while (matchFound) {
3556 matchFound = false;
3557 mDrawingState.traverseInZOrder([&](Layer* layer) {
3558 if (layer->getName() == uniqueName) {
3559 matchFound = true;
3560 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3561 }
3562 });
3563 }
3564
3565 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3566
3567 return uniqueName;
3568}
3569
David Sodman0c69cad2017-08-21 12:12:51 -07003570status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003571 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3572 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003573{
3574 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003575 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003576 case PIXEL_FORMAT_TRANSPARENT:
3577 case PIXEL_FORMAT_TRANSLUCENT:
3578 format = PIXEL_FORMAT_RGBA_8888;
3579 break;
3580 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003581 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003582 break;
3583 }
3584
David Sodman0c69cad2017-08-21 12:12:51 -07003585 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3586 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003587 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003588 *handle = layer->getHandle();
3589 *gbp = layer->getProducer();
3590 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003591 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003592
David Sodman0c69cad2017-08-21 12:12:51 -07003593 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003594 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003595}
3596
chaviw13fdc492017-06-27 12:40:18 -07003597status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003598 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003599 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003600{
chaviw13fdc492017-06-27 12:40:18 -07003601 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003602 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003603 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003604}
3605
Mathias Agopianac9fa422013-02-11 16:40:36 -08003606status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003607{
Robert Carr9524cb32017-02-13 11:32:32 -08003608 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003609 status_t err = NO_ERROR;
3610 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003611 if (l != nullptr) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003612 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003613 err = removeLayer(l);
3614 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3615 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003616 }
3617 return err;
3618}
3619
Mathias Agopian13127d82013-03-05 17:47:11 -08003620status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003621{
Mathias Agopian67106042013-03-14 19:18:13 -07003622 // called by ~LayerCleaner() when all references to the IBinder (handle)
3623 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003624 sp<Layer> l = layer.promote();
3625 if (l == nullptr) {
3626 // The layer has already been removed, carry on
3627 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003628 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003629 // If we have a parent, then we can continue to live as long as it does.
3630 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003631}
3632
Mathias Agopianb60314a2012-04-10 22:09:54 -07003633// ---------------------------------------------------------------------------
3634
Andy McFadden13a082e2012-08-24 10:16:42 -07003635void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003636 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003637 Vector<ComposerState> state;
3638 Vector<DisplayState> displays;
3639 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003640 d.what = DisplayState::eDisplayProjectionChanged |
3641 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003642 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003643 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003644 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003645 d.frame.makeInvalid();
3646 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003647 d.width = 0;
3648 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003649 displays.add(d);
3650 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003651 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3652 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003653
David Sodman105b7dc2017-11-04 20:28:14 -07003654 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003655 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003656 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003657
Brian Andersond0010582017-03-07 13:20:31 -08003658 // Use phase of 0 since phase is not known.
3659 // Use latency of 0, which will snap to the ideal latency.
3660 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003661}
3662
3663void SurfaceFlinger::initializeDisplays() {
3664 class MessageScreenInitialized : public MessageBase {
3665 SurfaceFlinger* flinger;
3666 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003667 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003668 virtual bool handler() {
3669 flinger->onInitializeDisplays();
3670 return true;
3671 }
3672 };
3673 sp<MessageBase> msg = new MessageScreenInitialized(this);
3674 postMessageAsync(msg); // we may be called from main thread, use async message
3675}
3676
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003677void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003678 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003679 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3680 this);
3681 int32_t type = hw->getDisplayType();
3682 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003683
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003684 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003685 return;
3686 }
3687
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003688 hw->setPowerMode(mode);
3689 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3690 ALOGW("Trying to set power mode for virtual display");
3691 return;
3692 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003693
Lloyd Pique4d234852018-01-22 17:21:36 -08003694 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003695 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003696 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3697 if (idx < 0) {
3698 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3699 return;
3700 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003701 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003702 }
3703
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003704 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003705 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003706 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003707 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3708 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003709 // FIXME: eventthread only knows about the main display right now
3710 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003711 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003712 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003713
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003714 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003715 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003716 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003717
3718 struct sched_param param = {0};
3719 param.sched_priority = 1;
3720 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3721 ALOGW("Couldn't set SCHED_FIFO on display on");
3722 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003723 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003724 // Turn off the display
3725 struct sched_param param = {0};
3726 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3727 ALOGW("Couldn't set SCHED_OTHER on display off");
3728 }
3729
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003730 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3731 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003732 disableHardwareVsync(true); // also cancels any in-progress resync
3733
Mathias Agopiancde87a32012-09-13 14:09:01 -07003734 // FIXME: eventthread only knows about the main display right now
3735 mEventThread->onScreenReleased();
3736 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003737
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003738 getHwComposer().setPowerMode(type, mode);
3739 mVisibleRegionsDirty = true;
3740 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003741 } else if (mode == HWC_POWER_MODE_DOZE ||
3742 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003743 // Update display while dozing
3744 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003745 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3746 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003747 // FIXME: eventthread only knows about the main display right now
3748 mEventThread->onScreenAcquired();
3749 resyncToHardwareVsync(true);
3750 }
3751 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3752 // Leave display going to doze
3753 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3754 disableHardwareVsync(true); // also cancels any in-progress resync
3755 // FIXME: eventthread only knows about the main display right now
3756 mEventThread->onScreenReleased();
3757 }
3758 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003759 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003760 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003761 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003762 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003763 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003764}
3765
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003766void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3767 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003768 SurfaceFlinger& mFlinger;
3769 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003770 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003771 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003772 MessageSetPowerMode(SurfaceFlinger& flinger,
3773 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3774 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003775 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003776 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003777 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003778 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003779 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003780 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003781 ALOGW("Attempt to set power mode = %d for virtual display",
3782 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003783 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003784 mFlinger.setPowerModeInternal(
3785 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003786 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003787 return true;
3788 }
3789 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003790 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003791 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003792}
3793
3794// ---------------------------------------------------------------------------
3795
Lloyd Pique755e3192018-01-31 16:46:15 -08003796status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3797 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003798 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003799
Mathias Agopianbd115332013-04-18 16:41:04 -07003800 IPCThreadState* ipc = IPCThreadState::self();
3801 const int pid = ipc->getCallingPid();
3802 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003803
Mathias Agopianbd115332013-04-18 16:41:04 -07003804 if ((uid != AID_SHELL) &&
3805 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003806 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003807 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003808 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003809 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003810 // (this would indicate SF is stuck, but we want to be able to
3811 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003812 status_t err = mStateLock.timedLock(s2ns(1));
3813 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003814 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003815 result.appendFormat(
3816 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3817 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003818 }
3819
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003820 bool dumpAll = true;
3821 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003822 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003823
3824 if (asProto) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003825 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviwa3d7bd32017-11-03 09:41:53 -07003826 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3827 dumpAll = false;
3828 }
3829
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003830 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003831 if ((index < numArgs) &&
3832 (args[index] == String16("--list"))) {
3833 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003834 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003835 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003836 }
3837
3838 if ((index < numArgs) &&
3839 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003840 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003841 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003842 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003843 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003844
3845 if ((index < numArgs) &&
3846 (args[index] == String16("--latency-clear"))) {
3847 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003848 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003849 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003850 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003851
3852 if ((index < numArgs) &&
3853 (args[index] == String16("--dispsync"))) {
3854 index++;
3855 mPrimaryDispSync.dump(result);
3856 dumpAll = false;
3857 }
Dan Stozab90cf072015-03-05 11:05:59 -08003858
3859 if ((index < numArgs) &&
3860 (args[index] == String16("--static-screen"))) {
3861 index++;
3862 dumpStaticScreenStats(result);
3863 dumpAll = false;
3864 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003865
3866 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003867 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003868 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003869 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003870 dumpAll = false;
3871 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003872
3873 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3874 index++;
3875 dumpWideColorInfo(result);
3876 dumpAll = false;
3877 }
Yiwei Zhang068e31b2018-02-21 13:02:45 -08003878
3879 if ((index < numArgs) &&
3880 (args[index] == String16("--enable-layer-stats"))) {
3881 index++;
3882 mLayerStats.enable();
3883 dumpAll = false;
3884 }
3885
3886 if ((index < numArgs) &&
3887 (args[index] == String16("--disable-layer-stats"))) {
3888 index++;
3889 mLayerStats.disable();
3890 dumpAll = false;
3891 }
3892
3893 if ((index < numArgs) &&
3894 (args[index] == String16("--clear-layer-stats"))) {
3895 index++;
3896 mLayerStats.clear();
3897 dumpAll = false;
3898 }
3899
3900 if ((index < numArgs) &&
3901 (args[index] == String16("--dump-layer-stats"))) {
3902 index++;
3903 mLayerStats.dump(result);
3904 dumpAll = false;
3905 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003906 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003907
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003908 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003909 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003910 }
3911
Mathias Agopian9795c422009-08-26 16:36:26 -07003912 if (locked) {
3913 mStateLock.unlock();
3914 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003915 }
3916 write(fd, result.string(), result.size());
3917 return NO_ERROR;
3918}
3919
Dan Stozac7014012014-02-14 15:03:43 -08003920void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3921 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003922{
Robert Carr2047fae2016-11-28 14:09:09 -08003923 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003924 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003925 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003926}
3927
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003928void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003929 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003930{
3931 String8 name;
3932 if (index < args.size()) {
3933 name = String8(args[index]);
3934 index++;
3935 }
3936
David Sodman105b7dc2017-11-04 20:28:14 -07003937 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003938 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003939 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003940
3941 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003942 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003943 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003944 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003945 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003946 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003947 }
Robert Carr2047fae2016-11-28 14:09:09 -08003948 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003949 }
3950}
3951
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003952void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003953 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003954{
3955 String8 name;
3956 if (index < args.size()) {
3957 name = String8(args[index]);
3958 index++;
3959 }
3960
Robert Carr2047fae2016-11-28 14:09:09 -08003961 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003962 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003963 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003964 }
Robert Carr2047fae2016-11-28 14:09:09 -08003965 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003966
Svetoslavd85084b2014-03-20 10:28:31 -07003967 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003968}
3969
Jamie Gennis6547ff42013-07-16 20:12:42 -07003970// This should only be called from the main thread. Otherwise it would need
3971// the lock and should use mCurrentState rather than mDrawingState.
3972void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003973 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003974 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003975 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003976
3977 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3978}
3979
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003980void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003981{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003982 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003983
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003984 if (isLayerTripleBufferingDisabled())
3985 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003986
3987 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003988 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003989 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003990 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003991 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3992 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003993 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003994}
3995
Dan Stozab90cf072015-03-05 11:05:59 -08003996void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3997{
3998 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003999 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4000 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004001 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004002 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004003 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4004 b + 1, bucketTimeSec, percent);
4005 }
David Sodman4a36e932017-11-07 14:29:47 -08004006 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004007 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004008 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004009 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004010 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004011}
4012
Dan Stozae77c7662016-05-13 11:37:28 -07004013void SurfaceFlinger::recordBufferingStats(const char* layerName,
4014 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004015 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4016 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004017 for (const auto& segment : history) {
4018 if (!segment.usedThirdBuffer) {
4019 stats.twoBufferTime += segment.totalTime;
4020 }
4021 if (segment.occupancyAverage < 1.0f) {
4022 stats.doubleBufferedTime += segment.totalTime;
4023 } else if (segment.occupancyAverage < 2.0f) {
4024 stats.tripleBufferedTime += segment.totalTime;
4025 }
4026 ++stats.numSegments;
4027 stats.totalTime += segment.totalTime;
4028 }
4029}
4030
Brian Andersond6927fb2016-07-23 23:37:30 -07004031void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4032 result.appendFormat("Layer frame timestamps:\n");
4033
4034 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4035 const size_t count = currentLayers.size();
4036 for (size_t i=0 ; i<count ; i++) {
4037 currentLayers[i]->dumpFrameEvents(result);
4038 }
4039}
4040
Dan Stozae77c7662016-05-13 11:37:28 -07004041void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4042 result.append("Buffering stats:\n");
4043 result.append(" [Layer name] <Active time> <Two buffer> "
4044 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004045 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004046 typedef std::tuple<std::string, float, float, float> BufferTuple;
4047 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004048 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004049 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004050 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004051 if (stats.numSegments == 0) {
4052 continue;
4053 }
4054 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4055 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4056 stats.totalTime;
4057 float doubleBufferRatio = static_cast<float>(
4058 stats.doubleBufferedTime) / stats.totalTime;
4059 float tripleBufferRatio = static_cast<float>(
4060 stats.tripleBufferedTime) / stats.totalTime;
4061 sorted.insert({activeTime, {name, twoBufferRatio,
4062 doubleBufferRatio, tripleBufferRatio}});
4063 }
4064 for (const auto& sortedPair : sorted) {
4065 float activeTime = sortedPair.first;
4066 const BufferTuple& values = sortedPair.second;
4067 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4068 std::get<0>(values).c_str(), activeTime,
4069 std::get<1>(values), std::get<2>(values),
4070 std::get<3>(values));
4071 }
4072 result.append("\n");
4073}
4074
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004075void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4076 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004077 result.appendFormat("DisplayColorSetting: %d\n", mDisplayColorSetting);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004078
4079 // TODO: print out if wide-color mode is active or not
4080
4081 for (size_t d = 0; d < mDisplays.size(); d++) {
4082 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4083 int32_t hwcId = displayDevice->getHwcDisplayId();
4084 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4085 continue;
4086 }
4087
4088 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004089 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004090 for (auto&& mode : modes) {
4091 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4092 }
4093
Peiyong Lina52f0292018-03-14 17:26:31 -07004094 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004095 result.appendFormat(" Current color mode: %s (%d)\n",
4096 decodeColorMode(currentMode).c_str(), currentMode);
4097 }
4098 result.append("\n");
4099}
4100
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004101LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004102 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004103 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4104 const State& state = useDrawing ? mDrawingState : mCurrentState;
4105 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004106 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004107 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004108 });
4109
4110 return layersProto;
4111}
4112
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004113LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4114 LayersProto layersProto;
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004115 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004116
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004117 SizeProto* resolution = layersProto.mutable_resolution();
4118 resolution->set_w(displayDevice->getWidth());
4119 resolution->set_h(displayDevice->getHeight());
4120
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004121 layersProto.set_color_mode(decodeColorMode(displayDevice->getActiveColorMode()));
4122 layersProto.set_color_transform(decodeColorTransform(displayDevice->getColorTransform()));
4123 layersProto.set_global_transform(
4124 static_cast<int32_t>(displayDevice->getOrientationTransform()));
4125
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004126 mDrawingState.traverseInZOrder([&](Layer* layer) {
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004127 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004128 LayerProto* layerProto = layersProto.add_layers();
4129 layer->writeToProto(layerProto, hwcId);
4130 }
4131 });
4132
4133 return layersProto;
4134}
4135
Mathias Agopian74d211a2013-04-22 16:55:35 +02004136void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4137 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004138{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004139 bool colorize = false;
4140 if (index < args.size()
4141 && (args[index] == String16("--color"))) {
4142 colorize = true;
4143 index++;
4144 }
4145
4146 Colorizer colorizer(colorize);
4147
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004148 // figure out if we're stuck somewhere
4149 const nsecs_t now = systemTime();
4150 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4151 const nsecs_t inTransaction(mDebugInTransaction);
4152 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4153 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4154
4155 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004156 * Dump library configuration.
4157 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004158
4159 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004160 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004161 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004162 appendSfConfigString(result);
4163 appendUiConfigString(result);
4164 appendGuiConfigString(result);
4165 result.append("\n");
4166
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004167 result.append("\nWide-Color information:\n");
4168 dumpWideColorInfo(result);
4169
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004170 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004171 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004172 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004173 result.append(SyncFeatures::getInstance().toString());
4174 result.append("\n");
4175
David Sodman105b7dc2017-11-04 20:28:14 -07004176 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004177
Andy McFadden41d67d72014-04-25 16:58:34 -07004178 colorizer.bold(result);
4179 result.append("DispSync configuration: ");
4180 colorizer.reset(result);
Dan Stoza2713c302018-03-28 17:07:36 -07004181 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, early sf phase %" PRId64
4182 " ns, present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4183 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, mVsyncModulator.getEarlyPhaseOffset(),
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004184 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004185 result.append("\n");
4186
Dan Stozab90cf072015-03-05 11:05:59 -08004187 // Dump static screen stats
4188 result.append("\n");
4189 dumpStaticScreenStats(result);
4190 result.append("\n");
4191
Dan Stozae77c7662016-05-13 11:37:28 -07004192 dumpBufferingStats(result);
4193
Andy McFadden4803b742012-09-24 19:07:20 -07004194 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004195 * Dump the visible layer list
4196 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004197 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004198 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004199 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4200 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004201 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004202
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004203 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004204 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7794ec12018-03-14 13:28:39 -07004205 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004206 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004207
4208 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004209 * Dump Display state
4210 */
4211
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004212 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004213 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004214 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004215 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4216 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004217 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004218 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004219 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004220
4221 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004222 * Dump SurfaceFlinger global state
4223 */
4224
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004225 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004226 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004227 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004228
Mathias Agopian888c8222012-08-04 21:10:38 -07004229 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004230 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004231
David Sodmanbc815282017-11-05 18:57:52 -08004232 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004233
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004234 if (hw) {
4235 hw->undefinedRegion.dump(result, "undefinedRegion");
4236 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4237 hw->getOrientation(), hw->isDisplayOn());
4238 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004239 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004240 " last eglSwapBuffers() time: %f us\n"
4241 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004242 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004243 " refresh-rate : %f fps\n"
4244 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004245 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004246 " gpu_to_cpu_unsupported : %d\n"
4247 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004248 mLastSwapBufferTime/1000.0,
4249 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004250 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004251 1e9 / activeConfig->getVsyncPeriod(),
4252 activeConfig->getDpiX(),
4253 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004254 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004255
Mathias Agopian74d211a2013-04-22 16:55:35 +02004256 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004257 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004258
Mathias Agopian74d211a2013-04-22 16:55:35 +02004259 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004260 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004261
4262 /*
4263 * VSYNC state
4264 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004265 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004266 result.append("\n");
4267
4268 /*
4269 * HWC layer minidump
4270 */
4271 for (size_t d = 0; d < mDisplays.size(); d++) {
4272 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4273 int32_t hwcId = displayDevice->getHwcDisplayId();
4274 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4275 continue;
4276 }
4277
4278 result.appendFormat("Display %d HWC layers:\n", hwcId);
4279 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004280 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004281 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004282 });
Dan Stozae22aec72016-08-01 13:20:59 -07004283 result.append("\n");
4284 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004285
4286 /*
4287 * Dump HWComposer state
4288 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004289 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004290 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004291 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004292 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004293 result.appendFormat(" h/w composer %s\n",
4294 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004295 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004296
4297 /*
4298 * Dump gralloc state
4299 */
4300 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4301 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004302
4303 /*
4304 * Dump VrFlinger state if in use.
4305 */
4306 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4307 result.append("VrFlinger state:\n");
4308 result.append(mVrFlinger->Dump().c_str());
4309 result.append("\n");
4310 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004311}
4312
Mathias Agopian13127d82013-03-05 17:47:11 -08004313const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004314SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004315 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004316 wp<IBinder> dpy;
4317 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4318 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4319 dpy = mDisplays.keyAt(i);
4320 break;
4321 }
4322 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004323 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004324 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4325 // Just use the primary display so we have something to return
4326 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4327 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004328 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004329}
4330
Keun young Park63f165f2012-08-31 10:53:36 -07004331bool SurfaceFlinger::startDdmConnection()
4332{
4333 void* libddmconnection_dso =
4334 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4335 if (!libddmconnection_dso) {
4336 return false;
4337 }
4338 void (*DdmConnection_start)(const char* name);
4339 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004340 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004341 if (!DdmConnection_start) {
4342 dlclose(libddmconnection_dso);
4343 return false;
4344 }
4345 (*DdmConnection_start)(getServiceName());
4346 return true;
4347}
4348
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004349status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004350 switch (code) {
4351 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004352 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004353 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004354 case CLEAR_ANIMATION_FRAME_STATS:
4355 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004356 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004357 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004358 case ENABLE_VSYNC_INJECTIONS:
4359 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004360 {
4361 // codes that require permission check
4362 IPCThreadState* ipc = IPCThreadState::self();
4363 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004364 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004365 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004366 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004367 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004368 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004369 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004370 break;
4371 }
Robert Carr1db73f62016-12-21 12:58:51 -08004372 /*
4373 * Calling setTransactionState is safe, because you need to have been
4374 * granted a reference to Client* and Handle* to do anything with it.
4375 *
4376 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4377 */
4378 case SET_TRANSACTION_STATE:
4379 case CREATE_SCOPED_CONNECTION:
4380 {
4381 return OK;
4382 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004383 case CAPTURE_SCREEN:
4384 {
4385 // codes that require permission check
4386 IPCThreadState* ipc = IPCThreadState::self();
4387 const int pid = ipc->getCallingPid();
4388 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004389 if ((uid != AID_GRAPHICS) &&
4390 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004391 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004392 return PERMISSION_DENIED;
4393 }
4394 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004395 }
chaviwa76b2712017-09-20 12:02:26 -07004396 case CAPTURE_LAYERS: {
4397 IPCThreadState* ipc = IPCThreadState::self();
4398 const int pid = ipc->getCallingPid();
4399 const int uid = ipc->getCallingUid();
4400 if ((uid != AID_GRAPHICS) &&
4401 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4402 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4403 return PERMISSION_DENIED;
4404 }
4405 break;
4406 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004407 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004408 return OK;
4409}
4410
4411status_t SurfaceFlinger::onTransact(
4412 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4413{
4414 status_t credentialCheck = CheckTransactCodeCredentials(code);
4415 if (credentialCheck != OK) {
4416 return credentialCheck;
4417 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004418
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004419 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4420 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004421 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004422 IPCThreadState* ipc = IPCThreadState::self();
4423 const int uid = ipc->getCallingUid();
4424 if (CC_UNLIKELY(uid != AID_SYSTEM
4425 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004426 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004427 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004428 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004429 return PERMISSION_DENIED;
4430 }
4431 int n;
4432 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004433 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004434 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004435 return NO_ERROR;
4436 case 1002: // SHOW_UPDATES
4437 n = data.readInt32();
4438 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004439 invalidateHwcGeometry();
4440 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004441 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004442 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004443 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004444 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004445 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004446 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004447 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004448 setTransactionFlags(
4449 eTransactionNeeded|
4450 eDisplayTransactionNeeded|
4451 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004452 return NO_ERROR;
4453 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004454 case 1006:{ // send empty update
4455 signalRefresh();
4456 return NO_ERROR;
4457 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004458 case 1008: // toggle use of hw composer
4459 n = data.readInt32();
4460 mDebugDisableHWC = n ? 1 : 0;
4461 invalidateHwcGeometry();
4462 repaintEverything();
4463 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004464 case 1009: // toggle use of transform hint
4465 n = data.readInt32();
4466 mDebugDisableTransformHint = n ? 1 : 0;
4467 invalidateHwcGeometry();
4468 repaintEverything();
4469 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004470 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004471 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004472 reply->writeInt32(0);
4473 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004474 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004475 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004476 return NO_ERROR;
4477 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004478 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004479 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004480 return NO_ERROR;
4481 }
4482 case 1014: {
4483 // daltonize
4484 n = data.readInt32();
4485 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004486 case 1:
4487 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4488 break;
4489 case 2:
4490 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4491 break;
4492 case 3:
4493 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4494 break;
4495 default:
4496 mDaltonizer.setType(ColorBlindnessType::None);
4497 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004498 }
4499 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004500 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004501 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004502 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004503 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004504 invalidateHwcGeometry();
4505 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004506 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004507 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004508 case 1015: {
4509 // apply a color matrix
4510 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004511 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004512 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004513 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004514 for (size_t j = 0; j < 4; j++) {
4515 mColorMatrix[i][j] = data.readFloat();
4516 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004517 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004518 } else {
4519 mColorMatrix = mat4();
4520 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004521
4522 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4523 // the division by w in the fragment shader
4524 float4 lastRow(transpose(mColorMatrix)[3]);
4525 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4526 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4527 }
4528
Alan Viverette9c5a3332013-09-12 20:04:35 -07004529 invalidateHwcGeometry();
4530 repaintEverything();
4531 return NO_ERROR;
4532 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004533 // This is an experimental interface
4534 // Needs to be shifted to proper binder interface when we productize
4535 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004536 n = data.readInt32();
4537 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004538 return NO_ERROR;
4539 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004540 case 1017: {
4541 n = data.readInt32();
4542 mForceFullDamage = static_cast<bool>(n);
4543 return NO_ERROR;
4544 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004545 case 1018: { // Modify Choreographer's phase offset
4546 n = data.readInt32();
4547 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4548 return NO_ERROR;
4549 }
4550 case 1019: { // Modify SurfaceFlinger's phase offset
4551 n = data.readInt32();
4552 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4553 return NO_ERROR;
4554 }
Irvel468051e2016-06-13 16:44:44 -07004555 case 1020: { // Layer updates interceptor
4556 n = data.readInt32();
4557 if (n) {
4558 ALOGV("Interceptor enabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004559 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004560 }
4561 else{
4562 ALOGV("Interceptor disabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004563 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004564 }
4565 return NO_ERROR;
4566 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004567 case 1021: { // Disable HWC virtual displays
4568 n = data.readInt32();
4569 mUseHwcVirtualDisplays = !n;
4570 return NO_ERROR;
4571 }
Romain Guy0147a172017-06-01 13:53:56 -07004572 case 1022: { // Set saturation boost
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004573 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004574
4575 invalidateHwcGeometry();
4576 repaintEverything();
4577 return NO_ERROR;
4578 }
Romain Guy54f154a2017-10-24 21:40:32 +01004579 case 1023: { // Set native mode
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004580 int32_t value = data.readInt32();
4581 if (value > 2) {
4582 return BAD_VALUE;
4583 }
4584 if (value == 2 && !mBuiltinDisplaySupportsEnhance) {
4585 return BAD_VALUE;
4586 }
Romain Guy54f154a2017-10-24 21:40:32 +01004587
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004588 mDisplayColorSetting = toDisplayColorSetting(value);
Romain Guy54f154a2017-10-24 21:40:32 +01004589 invalidateHwcGeometry();
4590 repaintEverything();
4591 return NO_ERROR;
4592 }
4593 case 1024: { // Is wide color gamut rendering/color management supported?
4594 reply->writeBool(hasWideColorDisplay);
4595 return NO_ERROR;
4596 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004597 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004598 n = data.readInt32();
4599 if (n) {
4600 ALOGV("LayerTracing enabled");
4601 mTracing.enable();
4602 doTracing("tracing.enable");
4603 reply->writeInt32(NO_ERROR);
4604 } else {
4605 ALOGV("LayerTracing disabled");
4606 status_t err = mTracing.disable();
4607 reply->writeInt32(err);
4608 }
4609 return NO_ERROR;
4610 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004611 case 1026: { // Get layer tracing status
4612 reply->writeBool(mTracing.isEnabled());
4613 return NO_ERROR;
4614 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004615 // Is a DisplayColorSetting supported?
4616 case 1027: {
4617 int32_t value = data.readInt32();
4618 switch (value) {
4619 case 0:
4620 reply->writeBool(hasWideColorDisplay);
4621 return NO_ERROR;
4622 case 1:
4623 reply->writeBool(true);
4624 return NO_ERROR;
4625 case 2:
4626 reply->writeBool(mBuiltinDisplaySupportsEnhance);
4627 return NO_ERROR;
4628 default:
4629 return BAD_VALUE;
4630 }
4631 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004632 }
4633 }
4634 return err;
4635}
4636
Steven Thomas6d8110b2017-08-31 18:24:21 -07004637void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004638 android_atomic_or(1, &mRepaintEverything);
Jeffrey Kardatzkea9dcf112018-04-03 10:45:55 -07004639 for (size_t dpy = 0; dpy < mDisplays.size(); dpy++) {
4640 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
4641 const Rect bounds(displayDevice->getBounds());
4642 displayDevice->dirtyRegion.orSelf(Region(bounds));
4643 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004644 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004645}
4646
Steven Thomas6d8110b2017-08-31 18:24:21 -07004647void SurfaceFlinger::repaintEverything() {
4648 ConditionalLock _l(mStateLock,
4649 std::this_thread::get_id() != mMainThreadId);
4650 repaintEverythingLocked();
4651}
4652
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004653// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4654class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004655public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004656 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4657 ~WindowDisconnector() {
4658 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004659 }
4660
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004661private:
4662 ANativeWindow* mWindow;
4663 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004664};
4665
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004666status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4667 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4668 int32_t minLayerZ, int32_t maxLayerZ,
4669 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004670 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004671 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004672
chaviwa76b2712017-09-20 12:02:26 -07004673 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4674
4675 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004676 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4677
chaviwa76b2712017-09-20 12:02:26 -07004678 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4679
4680 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4681 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004682 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004683}
4684
4685status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004686 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004687 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004688 ATRACE_CALL();
4689
4690 class LayerRenderArea : public RenderArea {
4691 public:
Robert Carr578038f2018-03-09 12:25:24 -08004692 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4693 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
4694 : RenderArea(reqHeight, reqWidth),
4695 mLayer(layer),
4696 mCrop(crop),
4697 mFlinger(flinger),
4698 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004699 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004700 Rect getBounds() const override {
4701 const Layer::State& layerState(mLayer->getDrawingState());
4702 return Rect(layerState.active.w, layerState.active.h);
4703 }
4704 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4705 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4706 bool isSecure() const override { return false; }
4707 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004708 Rect getSourceCrop() const override {
4709 if (mCrop.isEmpty()) {
4710 return getBounds();
4711 } else {
4712 return mCrop;
4713 }
4714 }
4715 bool getWideColorSupport() const override { return false; }
4716 Dataspace getDataSpace() const override { return Dataspace::UNKNOWN; }
Robert Carr578038f2018-03-09 12:25:24 -08004717
4718 class ReparentForDrawing {
4719 public:
4720 const sp<Layer>& oldParent;
4721 const sp<Layer>& newParent;
4722
4723 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4724 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004725 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004726 }
Robert Carr15eae092018-03-23 13:43:53 -07004727 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004728 };
4729
4730 void render(std::function<void()> drawLayers) override {
4731 if (!mChildrenOnly) {
4732 mTransform = mLayer->getTransform().inverse();
4733 drawLayers();
4734 } else {
4735 Rect bounds = getBounds();
4736 screenshotParentLayer =
4737 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4738 bounds.getWidth(), bounds.getHeight(), 0);
4739
4740 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4741 drawLayers();
4742 }
4743 }
chaviwa76b2712017-09-20 12:02:26 -07004744
chaviwa76b2712017-09-20 12:02:26 -07004745 private:
chaviw7206d492017-11-10 16:16:12 -08004746 const sp<Layer> mLayer;
4747 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004748
4749 // In the "childrenOnly" case we reparent the children to a screenshot
4750 // layer which has no properties set and which does not draw.
4751 sp<ContainerLayer> screenshotParentLayer;
4752 Transform mTransform;
4753
4754 SurfaceFlinger* mFlinger;
4755 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004756 };
4757
4758 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4759 auto parent = layerHandle->owner.promote();
4760
chaviw7206d492017-11-10 16:16:12 -08004761 if (parent == nullptr || parent->isPendingRemoval()) {
4762 ALOGE("captureLayers called with a removed parent");
4763 return NAME_NOT_FOUND;
4764 }
4765
Robert Carr578038f2018-03-09 12:25:24 -08004766 const int uid = IPCThreadState::self()->getCallingUid();
4767 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4768 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4769 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4770 return PERMISSION_DENIED;
4771 }
4772
chaviw7206d492017-11-10 16:16:12 -08004773 Rect crop(sourceCrop);
4774 if (sourceCrop.width() <= 0) {
4775 crop.left = 0;
4776 crop.right = parent->getCurrentState().active.w;
4777 }
4778
4779 if (sourceCrop.height() <= 0) {
4780 crop.top = 0;
4781 crop.bottom = parent->getCurrentState().active.h;
4782 }
4783
4784 int32_t reqWidth = crop.width() * frameScale;
4785 int32_t reqHeight = crop.height() * frameScale;
4786
Robert Carr578038f2018-03-09 12:25:24 -08004787 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004788
Robert Carr578038f2018-03-09 12:25:24 -08004789 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004790 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4791 if (!layer->isVisible()) {
4792 return;
Robert Carr578038f2018-03-09 12:25:24 -08004793 } else if (childrenOnly && layer == parent.get()) {
4794 return;
chaviwa76b2712017-09-20 12:02:26 -07004795 }
4796 visitor(layer);
4797 });
4798 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004799 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004800}
4801
4802status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4803 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004804 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004805 bool useIdentityTransform) {
4806 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004807
chaviwa76b2712017-09-20 12:02:26 -07004808 renderArea.updateDimensions();
4809
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004810 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4811 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4812 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4813 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004814
4815 // This mutex protects syncFd and captureResult for communication of the return values from the
4816 // main thread back to this Binder thread
4817 std::mutex captureMutex;
4818 std::condition_variable captureCondition;
4819 std::unique_lock<std::mutex> captureLock(captureMutex);
4820 int syncFd = -1;
4821 std::optional<status_t> captureResult;
4822
Robert Carr03480e22018-01-04 16:02:06 -08004823 const int uid = IPCThreadState::self()->getCallingUid();
4824 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4825
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004826 sp<LambdaMessage> message = new LambdaMessage([&]() {
4827 // If there is a refresh pending, bug out early and tell the binder thread to try again
4828 // after the refresh.
4829 if (mRefreshPending) {
4830 ATRACE_NAME("Skipping screenshot for now");
4831 std::unique_lock<std::mutex> captureLock(captureMutex);
4832 captureResult = std::make_optional<status_t>(EAGAIN);
4833 captureCondition.notify_one();
4834 return;
4835 }
4836
4837 status_t result = NO_ERROR;
4838 int fd = -1;
4839 {
4840 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004841 renderArea.render([&]() {
4842 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4843 useIdentityTransform, forSystem, &fd);
4844 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004845 }
4846
4847 {
4848 std::unique_lock<std::mutex> captureLock(captureMutex);
4849 syncFd = fd;
4850 captureResult = std::make_optional<status_t>(result);
4851 captureCondition.notify_one();
4852 }
4853 });
4854
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004855 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004856 if (result == NO_ERROR) {
4857 captureCondition.wait(captureLock, [&]() { return captureResult; });
4858 while (*captureResult == EAGAIN) {
4859 captureResult.reset();
4860 result = postMessageAsync(message);
4861 if (result != NO_ERROR) {
4862 return result;
4863 }
4864 captureCondition.wait(captureLock, [&]() { return captureResult; });
4865 }
4866 result = *captureResult;
4867 }
4868
4869 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004870 sync_wait(syncFd, -1);
4871 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004872 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004873
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004874 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004875}
4876
chaviwa76b2712017-09-20 12:02:26 -07004877void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4878 TraverseLayersFunction traverseLayers, bool yswap,
4879 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004880 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004881
Lloyd Pique144e1162017-12-20 16:44:52 -08004882 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004883
4884 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004885 const auto raWidth = renderArea.getWidth();
4886 const auto raHeight = renderArea.getHeight();
4887
4888 const auto reqWidth = renderArea.getReqWidth();
4889 const auto reqHeight = renderArea.getReqHeight();
4890 Rect sourceCrop = renderArea.getSourceCrop();
4891
4892 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4893 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004894
Dan Stozac1879002014-05-22 15:59:05 -07004895 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004896 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004897 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004898 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004899 }
4900
4901 // ensure that sourceCrop is inside screen
4902 if (sourceCrop.left < 0) {
4903 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4904 }
chaviwa76b2712017-09-20 12:02:26 -07004905 if (sourceCrop.right > raWidth) {
4906 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004907 }
4908 if (sourceCrop.top < 0) {
4909 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4910 }
chaviwa76b2712017-09-20 12:02:26 -07004911 if (sourceCrop.bottom > raHeight) {
4912 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004913 }
4914
Peiyong Lin34beb7a2018-03-28 11:57:12 -07004915 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004916 if (renderArea.getWideColorSupport()) {
4917 outputDataspace = renderArea.getDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004918 }
4919 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Romain Guy88d37dd2017-05-26 17:57:05 -07004920
Mathias Agopian180f10d2013-04-10 22:55:41 -07004921 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004922 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004923
4924 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004925 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4926 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004927 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004928
4929 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004930 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004931
chaviwa76b2712017-09-20 12:02:26 -07004932 traverseLayers([&](Layer* layer) {
4933 if (filtering) layer->setFiltering(true);
4934 layer->draw(renderArea, useIdentityTransform);
4935 if (filtering) layer->setFiltering(false);
4936 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004937}
4938
chaviwa76b2712017-09-20 12:02:26 -07004939status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4940 TraverseLayersFunction traverseLayers,
4941 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004942 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08004943 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07004944 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004945 ATRACE_CALL();
4946
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004947 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004948
4949 traverseLayers([&](Layer* layer) {
4950 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4951 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004952
Robert Carr03480e22018-01-04 16:02:06 -08004953 // We allow the system server to take screenshots of secure layers for
4954 // use in situations like the Screen-rotation animation and place
4955 // the impetus on WindowManager to not persist them.
4956 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004957 ALOGW("FB is protected: PERMISSION_DENIED");
4958 return PERMISSION_DENIED;
4959 }
4960
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004961 // this binds the given EGLImage as a framebuffer for the
4962 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08004963 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08004964 if (bufferBond.getStatus() != NO_ERROR) {
4965 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004966 return INVALID_OPERATION;
4967 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004968
Dan Stozaabcda352017-06-01 14:37:39 -07004969 // this will in fact render into our dequeued buffer
4970 // via an FBO, which means we didn't have to create
4971 // an EGLSurface and therefore we're not
4972 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004973 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004974
Dan Stozaabcda352017-06-01 14:37:39 -07004975 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08004976 getRenderEngine().finish();
4977 *outSyncFd = -1;
4978
chaviwa76b2712017-09-20 12:02:26 -07004979 const auto reqWidth = renderArea.getReqWidth();
4980 const auto reqHeight = renderArea.getReqHeight();
4981
Dan Stozaabcda352017-06-01 14:37:39 -07004982 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4983 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004984 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004985 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08004986 } else {
4987 base::unique_fd syncFd = getRenderEngine().flush();
4988 if (syncFd < 0) {
4989 getRenderEngine().finish();
4990 }
4991 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07004992 }
4993
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004994 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004995}
4996
Mathias Agopiand5556842013-09-19 17:08:37 -07004997void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07004998 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004999 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005000 for (size_t y = 0; y < h; y++) {
5001 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5002 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005003 if (p[x] != 0xFF000000) return;
5004 }
5005 }
chaviwa76b2712017-09-20 12:02:26 -07005006 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005007
Robert Carr2047fae2016-11-28 14:09:09 -08005008 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005009 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005010 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005011 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5012 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5013 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5014 static_cast<float>(state.color.a));
5015 i++;
5016 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005017 }
5018}
5019
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005020// ---------------------------------------------------------------------------
5021
Dan Stoza412903f2017-04-27 13:42:17 -07005022void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5023 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005024}
5025
Dan Stoza412903f2017-04-27 13:42:17 -07005026void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5027 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005028}
5029
chaviwa76b2712017-09-20 12:02:26 -07005030void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
5031 int32_t maxLayerZ,
5032 const LayerVector::Visitor& visitor) {
5033 // We loop through the first level of layers without traversing,
5034 // as we need to interpret min/max layer Z in the top level Z space.
5035 for (const auto& layer : mDrawingState.layersSortedByZ) {
5036 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5037 continue;
5038 }
5039 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005040 // relative layers are traversed in Layer::traverseInZOrder
5041 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005042 continue;
5043 }
5044 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005045 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5046 return;
5047 }
chaviwa76b2712017-09-20 12:02:26 -07005048 if (!layer->isVisible()) {
5049 return;
5050 }
5051 visitor(layer);
5052 });
5053 }
5054}
5055
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005056}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005057
5058
5059#if defined(__gl_h_)
5060#error "don't include gl/gl.h in this file"
5061#endif
5062
5063#if defined(__gl2_h_)
5064#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005065#endif