blob: 57f729bf0b8aeddca48ea7308063bede93f55ec3 [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();
Peiyong Lin38e9a562018-04-10 16:24:20 -07001023 RenderIntent currentRenderIntent = hw->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001024
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001025 // Natural Mode means it's color managed and the color must be right,
1026 // thus we pick RenderIntent::COLORIMETRIC as render intent.
1027 // Native Mode means the display is not color managed, and whichever
1028 // render intent is picked doesn't matter, thus return
1029 // RenderIntent::COLORIMETRIC as default here.
1030 RenderIntent renderIntent = RenderIntent::COLORIMETRIC;
1031
1032 // In Auto Color Mode, we want to strech to panel color space, right now
1033 // only the built-in display supports it.
1034 if (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
1035 mBuiltinDisplaySupportsEnhance &&
1036 hw->getDisplayType() == DisplayDevice::DISPLAY_PRIMARY) {
1037 renderIntent = RenderIntent::ENHANCE;
1038 }
Peiyong Lin38e9a562018-04-10 16:24:20 -07001039
1040 if (mode == currentMode && dataSpace == currentDataSpace &&
1041 renderIntent == currentRenderIntent) {
1042 return;
1043 }
1044
1045 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1046 ALOGW("Trying to set config for virtual display");
1047 return;
1048 }
1049
1050 hw->setActiveColorMode(mode);
1051 hw->setCompositionDataSpace(dataSpace);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001052 hw->setActiveRenderIntent(renderIntent);
1053 getHwComposer().setActiveColorMode(type, mode, renderIntent);
1054
1055 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
1056 decodeColorMode(mode).c_str(), mode,
1057 decodeRenderIntent(renderIntent).c_str(), renderIntent,
1058 hw->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001059}
1060
1061
1062status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001063 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -07001064 class MessageSetActiveColorMode: public MessageBase {
1065 SurfaceFlinger& mFlinger;
1066 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -07001067 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001068 public:
1069 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -07001070 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -07001071 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1072 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -07001073 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001074 mFlinger.getDisplayColorModes(mDisplay, &modes);
1075 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -07001076 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001077 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1078 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001079 return true;
1080 }
1081 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1082 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001083 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1084 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001085 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001086 ALOGW("Attempt to set active color mode %s %d for virtual display",
1087 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001088 } else {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001089 mFlinger.setActiveColorModeInternal(hw, mMode, Dataspace::UNKNOWN);
Michael Wright28f24d02016-07-12 13:30:53 -07001090 }
1091 return true;
1092 }
1093 };
1094 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1095 postMessageSync(msg);
1096 return NO_ERROR;
1097}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001098
Svetoslavd85084b2014-03-20 10:28:31 -07001099status_t SurfaceFlinger::clearAnimationFrameStats() {
1100 Mutex::Autolock _l(mStateLock);
1101 mAnimFrameTracker.clearStats();
1102 return NO_ERROR;
1103}
1104
1105status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1106 Mutex::Autolock _l(mStateLock);
1107 mAnimFrameTracker.getStats(outStats);
1108 return NO_ERROR;
1109}
1110
Dan Stozac4f471e2016-03-24 09:31:08 -07001111status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1112 HdrCapabilities* outCapabilities) const {
1113 Mutex::Autolock _l(mStateLock);
1114
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001115 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001116 if (displayDevice == nullptr) {
1117 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1118 return BAD_VALUE;
1119 }
1120
1121 std::unique_ptr<HdrCapabilities> capabilities =
David Sodman105b7dc2017-11-04 20:28:14 -07001122 getBE().mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
Dan Stozac4f471e2016-03-24 09:31:08 -07001123 if (capabilities) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001124 if (displayDevice->hasWideColorGamut() && !displayDevice->hasHdr10()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001125 // insert HDR10 as we will force client composition for HDR10
1126 // layers
1127 std::vector<int32_t> types = capabilities->getSupportedHdrTypes();
1128 types.push_back(HAL_HDR_HDR10);
1129
1130 *outCapabilities = HdrCapabilities(types,
1131 capabilities->getDesiredMaxLuminance(),
1132 capabilities->getDesiredMaxAverageLuminance(),
1133 capabilities->getDesiredMinLuminance());
1134 } else {
1135 *outCapabilities = std::move(*capabilities);
1136 }
Dan Stozac4f471e2016-03-24 09:31:08 -07001137 } else {
1138 return BAD_VALUE;
1139 }
1140
1141 return NO_ERROR;
1142}
1143
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001144status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001145 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1146 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001147
Chia-I Wu90f669f2017-10-05 14:24:41 -07001148 if (mInjectVSyncs == enable) {
1149 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001150 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001151
1152 if (enable) {
1153 ALOGV("VSync Injections enabled");
1154 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001155 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique0fcde1b2017-12-20 16:50:21 -08001156 mInjectorEventThread =
1157 std::make_unique<impl::EventThread>(mVSyncInjector.get(), *this, false,
1158 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001159 }
Lloyd Pique9123ae52018-01-22 17:14:00 -08001160 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001161 } else {
1162 ALOGV("VSync Injections disabled");
Lloyd Pique9123ae52018-01-22 17:14:00 -08001163 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001164 }
1165
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001166 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001167 });
1168 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001169 return NO_ERROR;
1170}
1171
1172status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001173 Mutex::Autolock _l(mStateLock);
1174
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001175 if (!mInjectVSyncs) {
1176 ALOGE("VSync Injections not enabled");
1177 return BAD_VALUE;
1178 }
1179 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1180 ALOGV("Injecting VSync inside SurfaceFlinger");
1181 mVSyncInjector->onInjectSyncEvent(when);
1182 }
1183 return NO_ERROR;
1184}
1185
Lloyd Pique755e3192018-01-31 16:46:15 -08001186status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1187 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001188 IPCThreadState* ipc = IPCThreadState::self();
1189 const int pid = ipc->getCallingPid();
1190 const int uid = ipc->getCallingUid();
1191 if ((uid != AID_SHELL) &&
1192 !PermissionCache::checkPermission(sDump, pid, uid)) {
1193 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1194 return PERMISSION_DENIED;
1195 }
1196
1197 // Try to acquire a lock for 1s, fail gracefully
1198 const status_t err = mStateLock.timedLock(s2ns(1));
1199 const bool locked = (err == NO_ERROR);
1200 if (!locked) {
1201 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1202 return TIMED_OUT;
1203 }
1204
1205 outLayers->clear();
1206 mCurrentState.traverseInZOrder([&](Layer* layer) {
1207 outLayers->push_back(layer->getLayerDebugInfo());
1208 });
1209
1210 mStateLock.unlock();
1211 return NO_ERROR;
1212}
1213
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001214// ----------------------------------------------------------------------------
1215
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001216sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1217 ISurfaceComposer::VsyncSource vsyncSource) {
1218 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1219 return mSFEventThread->createEventConnection();
1220 } else {
1221 return mEventThread->createEventConnection();
1222 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001223}
1224
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001225// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001226
1227void SurfaceFlinger::waitForEvent() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001228 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001229}
1230
1231void SurfaceFlinger::signalTransaction() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001232 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001233}
1234
1235void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001236 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001237}
1238
1239void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001240 mRefreshPending = true;
Lloyd Pique9123ae52018-01-22 17:14:00 -08001241 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001242}
1243
1244status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001245 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001246 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001247}
1248
1249status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001250 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001251 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001252 if (res == NO_ERROR) {
1253 msg->wait();
1254 }
1255 return res;
1256}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001257
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001258void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001259 do {
1260 waitForEvent();
1261 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001262}
1263
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001264void SurfaceFlinger::enableHardwareVsync() {
1265 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001266 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001267 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001268 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1269 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001270 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001271 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001272}
1273
Jesse Hall948fe0c2013-10-14 12:56:09 -07001274void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001275 Mutex::Autolock _l(mHWVsyncLock);
1276
Jesse Hall948fe0c2013-10-14 12:56:09 -07001277 if (makeAvailable) {
1278 mHWVsyncAvailable = true;
1279 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001280 // Hardware vsync is not currently available, so abort the resync
1281 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001282 return;
1283 }
1284
David Sodman105b7dc2017-11-04 20:28:14 -07001285 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001286 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001287
1288 mPrimaryDispSync.reset();
1289 mPrimaryDispSync.setPeriod(period);
1290
1291 if (!mPrimaryHWVsyncEnabled) {
1292 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001293 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1294 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001295 mPrimaryHWVsyncEnabled = true;
1296 }
1297}
1298
Jesse Hall948fe0c2013-10-14 12:56:09 -07001299void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001300 Mutex::Autolock _l(mHWVsyncLock);
1301 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001302 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1303 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001304 mPrimaryDispSync.endResync();
1305 mPrimaryHWVsyncEnabled = false;
1306 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001307 if (makeUnavailable) {
1308 mHWVsyncAvailable = false;
1309 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001310}
1311
Tim Murray4a4e4a22016-04-19 16:29:23 +00001312void SurfaceFlinger::resyncWithRateLimit() {
1313 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001314
1315 // No explicit locking is needed here since EventThread holds a lock while calling this method
1316 static nsecs_t sLastResyncAttempted = 0;
1317 const nsecs_t now = systemTime();
1318 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001319 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001320 }
Dan Stoza57164302017-05-08 14:03:54 -07001321 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001322}
1323
Steven Thomasb02664d2017-07-26 18:48:28 -07001324void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1325 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001326 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001327 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001328 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001329 return;
1330 }
1331
1332 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001333 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001334 return;
1335 }
1336
Jamie Gennisd1700752013-10-14 12:22:52 -07001337 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001338
Jamie Gennisd1700752013-10-14 12:22:52 -07001339 { // Scope for the lock
1340 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001341 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001342 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001343 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001344 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001345
1346 if (needsHwVsync) {
1347 enableHardwareVsync();
1348 } else {
1349 disableHardwareVsync(false);
1350 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001351}
1352
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001353void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001354 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1355 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001356}
1357
Lloyd Pique715a2c12017-12-14 17:18:08 -08001358void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1359 HWC2::Connection connection) {
1360 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1361 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001362
Lloyd Piqueba04e622017-12-14 17:11:26 -08001363 // Ignore events that do not have the right sequenceId.
1364 if (sequenceId != getBE().mComposerSequenceId) {
1365 return;
1366 }
1367
Steven Thomasb02664d2017-07-26 18:48:28 -07001368 // Only lock if we're not on the main thread. This function is normally
1369 // called on a hwbinder thread, but for the primary display it's called on
1370 // the main thread with the state lock already held, so don't attempt to
1371 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001372 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001373
Lloyd Pique715a2c12017-12-14 17:18:08 -08001374 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001375
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001376 if (std::this_thread::get_id() == mMainThreadId) {
1377 // Process all pending hot plug events immediately if we are on the main thread.
1378 processDisplayHotplugEventsLocked();
1379 }
1380
Lloyd Piqueba04e622017-12-14 17:11:26 -08001381 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001382}
1383
Steven Thomasb02664d2017-07-26 18:48:28 -07001384void SurfaceFlinger::onRefreshReceived(int sequenceId,
1385 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001386 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001387 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001388 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001389 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001390 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001391}
1392
Dan Stoza9e56aa02015-11-02 13:00:03 -08001393void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001394 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001395 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001396 getHwComposer().setVsyncEnabled(disp,
1397 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001398}
1399
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001400// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001401void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001402 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001403 // Clear the drawing state so that the logic inside of
1404 // handleTransactionLocked will fire. It will determine the delta between
1405 // mCurrentState and mDrawingState and re-apply all changes when we make the
1406 // transition.
1407 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001408 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001409 mDisplays.clear();
1410}
1411
Steven Thomas050b2c82017-03-06 11:45:16 -08001412void SurfaceFlinger::updateVrFlinger() {
1413 if (!mVrFlinger)
1414 return;
1415 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001416 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001417 return;
1418 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001419
David Sodman105b7dc2017-11-04 20:28:14 -07001420 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001421 ALOGE("Vr flinger is only supported for remote hardware composer"
1422 " service connections. Ignoring request to transition to vr"
1423 " flinger.");
1424 mVrFlingerRequestsDisplay = false;
1425 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001426 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001427
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001428 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001429
Steven Thomasb02664d2017-07-26 18:48:28 -07001430 int currentDisplayPowerMode = getDisplayDeviceLocked(
1431 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001432
Steven Thomasb02664d2017-07-26 18:48:28 -07001433 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001434 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001435 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001436
Steven Thomasb02664d2017-07-26 18:48:28 -07001437 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001438 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001439 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1440 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001441 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001442
David Sodman105b7dc2017-11-04 20:28:14 -07001443 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1444 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001445
1446 if (vrFlingerRequestsDisplay) {
1447 mVrFlinger->GrantDisplayOwnership();
1448 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001449 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001450 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001451
1452 mVisibleRegionsDirty = true;
1453 invalidateHwcGeometry();
1454
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001455 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001456 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1457 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1458 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001459
Steven Thomasb02664d2017-07-26 18:48:28 -07001460 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001461 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001462 const nsecs_t period = activeConfig->getVsyncPeriod();
1463 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001464
Steven Thomasb02664d2017-07-26 18:48:28 -07001465 // Use phase of 0 since phase is not known.
1466 // Use latency of 0, which will snap to the ideal latency.
1467 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001468
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001469 android_atomic_or(1, &mRepaintEverything);
1470 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001471}
1472
Mathias Agopian4fec8732012-06-29 14:12:52 -07001473void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001474 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001475 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001476 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001477 bool frameMissed = !mHadClientComposition &&
1478 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001479 (mPreviousPresentFence->getSignalTime() ==
1480 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001481 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001482 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001483 signalLayerUpdate();
1484 break;
1485 }
1486
Steven Thomas050b2c82017-03-06 11:45:16 -08001487 // Now that we're going to make it to the handleMessageTransaction()
1488 // call below it's safe to call updateVrFlinger(), which will
1489 // potentially trigger a display handoff.
1490 updateVrFlinger();
1491
Dan Stoza6b9454d2014-11-07 16:00:59 -08001492 bool refreshNeeded = handleMessageTransaction();
1493 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001494 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001495 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001496 // Signal a refresh if a transaction modified the window state,
1497 // a new buffer was latched, or if HWC has requested a full
1498 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001499 signalRefresh();
1500 }
1501 break;
1502 }
1503 case MessageQueue::REFRESH: {
1504 handleMessageRefresh();
1505 break;
1506 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001507 }
1508}
1509
Dan Stoza6b9454d2014-11-07 16:00:59 -08001510bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001511 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001512 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001513 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001514 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001515 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001516 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001517}
1518
Dan Stoza6b9454d2014-11-07 16:00:59 -08001519bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001520 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001521 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001522}
1523
1524void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001525 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001526
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001527 mRefreshPending = false;
1528
Pablo Ceballos40845df2016-01-25 17:41:15 -08001529 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001530
Brian Andersond6927fb2016-07-23 23:37:30 -07001531 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001532 rebuildLayerStacks();
1533 setUpHWComposer();
1534 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001535 doTracing("handleRefresh");
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001536 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001537 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001538 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001539
David Sodman105b7dc2017-11-04 20:28:14 -07001540 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001541
1542 mHadClientComposition = false;
1543 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1544 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1545 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001546 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001547 }
Dan Stoza2713c302018-03-28 17:07:36 -07001548 mVsyncModulator.setLastFrameUsedRenderEngine(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001549
Dan Stoza9e56aa02015-11-02 13:00:03 -08001550 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001551}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001552
Mathias Agopiancd60f992012-08-16 16:28:27 -07001553void SurfaceFlinger::doDebugFlashRegions()
1554{
1555 // is debugging enabled
1556 if (CC_LIKELY(!mDebugRegion))
1557 return;
1558
1559 const bool repaintEverything = mRepaintEverything;
1560 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1561 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001562 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001563 // transform the dirty region into this screen's coordinate space
1564 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1565 if (!dirtyRegion.isEmpty()) {
1566 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001567 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001568
1569 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001570 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001571 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001572 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1573
Mathias Agopianda27af92012-09-13 18:17:13 -07001574 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001575 }
1576 }
1577 }
1578
1579 postFramebuffer();
1580
1581 if (mDebugRegion > 1) {
1582 usleep(mDebugRegion * 1000);
1583 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001584
Dan Stoza9e56aa02015-11-02 13:00:03 -08001585 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001586 auto& displayDevice = mDisplays[displayId];
1587 if (!displayDevice->isDisplayOn()) {
1588 continue;
1589 }
1590
David Sodman105b7dc2017-11-04 20:28:14 -07001591 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1592 ALOGE_IF(result != NO_ERROR,
1593 "prepareFrame for display %zd failed:"
1594 " %d (%s)",
1595 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001596 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001597}
1598
Adrian Roos1e1a1282017-11-01 19:05:31 +01001599void SurfaceFlinger::doTracing(const char* where) {
1600 ATRACE_CALL();
1601 ATRACE_NAME(where);
1602 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001603 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001604 }
1605}
1606
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001607void SurfaceFlinger::logLayerStats() {
1608 ATRACE_CALL();
1609 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1610 int32_t hwcId = -1;
1611 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1612 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1613 if (displayDevice->isPrimary()) {
1614 hwcId = displayDevice->getHwcDisplayId();
1615 break;
1616 }
1617 }
1618 if (hwcId < 0) {
1619 ALOGE("LayerStats: Hmmm, no primary display?");
1620 return;
1621 }
1622 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1623 }
1624}
1625
Brian Andersond6927fb2016-07-23 23:37:30 -07001626void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001627{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001628 ATRACE_CALL();
1629 ALOGV("preComposition");
1630
Mathias Agopiancd60f992012-08-16 16:28:27 -07001631 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001632 mDrawingState.traverseInZOrder([&](Layer* layer) {
1633 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001634 needExtraInvalidate = true;
1635 }
Robert Carr2047fae2016-11-28 14:09:09 -08001636 });
1637
Mathias Agopiancd60f992012-08-16 16:28:27 -07001638 if (needExtraInvalidate) {
1639 signalLayerUpdate();
1640 }
1641}
1642
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001643void SurfaceFlinger::updateCompositorTiming(
1644 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1645 std::shared_ptr<FenceTime>& presentFenceTime) {
1646 // Update queue of past composite+present times and determine the
1647 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001648 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001649 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001650 while (!getBE().mCompositePresentTimes.empty()) {
1651 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001652 // Cached values should have been updated before calling this method,
1653 // which helps avoid duplicate syscalls.
1654 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1655 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1656 break;
1657 }
1658 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001659 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001660 }
1661
1662 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001663 while (getBE().mCompositePresentTimes.size() > 16) {
1664 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001665 }
1666
Brian Andersond0010582017-03-07 13:20:31 -08001667 setCompositorTimingSnapped(
1668 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1669}
1670
1671void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1672 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001673 // Integer division and modulo round toward 0 not -inf, so we need to
1674 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001675 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001676 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1677 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1678
Brian Andersond0010582017-03-07 13:20:31 -08001679 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1680 if (idealLatency <= 0) {
1681 idealLatency = vsyncInterval;
1682 }
1683
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001684 // Snap the latency to a value that removes scheduling jitter from the
1685 // composition and present times, which often have >1ms of jitter.
1686 // Reducing jitter is important if an app attempts to extrapolate
1687 // something (such as user input) to an accurate diasplay time.
1688 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1689 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001690 nsecs_t bias = vsyncInterval / 2;
1691 int64_t extraVsyncs =
1692 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1693 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1694 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001695
David Sodman99974d22017-11-28 12:04:33 -08001696 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1697 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1698 getBE().mCompositorTiming.interval = vsyncInterval;
1699 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001700}
1701
1702void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001703{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001704 ATRACE_CALL();
1705 ALOGV("postComposition");
1706
Brian Anderson3546a3f2016-07-14 11:51:14 -07001707 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001708 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001709 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001710 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001711 }
1712
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001713 // |mStateLock| not needed as we are on the main thread
1714 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001715
David Sodman73beded2017-11-15 11:56:06 -08001716 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001717 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001718 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001719 glCompositionDoneFenceTime =
1720 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001721 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001722 } else {
1723 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1724 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001725
David Sodman73beded2017-11-15 11:56:06 -08001726 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001727 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001728 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001729 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001730
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001731 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1732 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1733
1734 // We use the refreshStartTime which might be sampled a little later than
1735 // when we started doing work for this frame, but that should be okay
1736 // since updateCompositorTiming has snapping logic.
1737 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001738 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001739 CompositorTiming compositorTiming;
1740 {
David Sodman99974d22017-11-28 12:04:33 -08001741 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1742 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001743 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001744
Robert Carr2047fae2016-11-28 14:09:09 -08001745 mDrawingState.traverseInZOrder([&](Layer* layer) {
1746 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001747 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001748 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001749 recordBufferingStats(layer->getName().string(),
1750 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001751 }
Robert Carr2047fae2016-11-28 14:09:09 -08001752 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001753
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001754 if (presentFenceTime->isValid()) {
1755 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001756 enableHardwareVsync();
1757 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001758 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001759 }
1760 }
1761
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001762 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001763 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001764 enableHardwareVsync();
1765 }
1766 }
1767
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001768 if (mAnimCompositionPending) {
1769 mAnimCompositionPending = false;
1770
Brian Anderson4e606e32017-03-16 15:34:57 -07001771 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001772 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001773 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001774 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001775 // The HWC doesn't support present fences, so use the refresh
1776 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001777 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001778 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001779 mAnimFrameTracker.setActualPresentTime(presentTime);
1780 }
1781 mAnimFrameTracker.advanceFrame();
1782 }
Dan Stozab90cf072015-03-05 11:05:59 -08001783
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001784 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1785 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001786 return;
1787 }
1788
1789 nsecs_t currentTime = systemTime();
1790 if (mHasPoweredOff) {
1791 mHasPoweredOff = false;
1792 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001793 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001794 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001795 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1796 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001797 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001798 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001799 }
David Sodman4a36e932017-11-07 14:29:47 -08001800 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001801 }
David Sodman4a36e932017-11-07 14:29:47 -08001802 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001803}
1804
1805void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001806 ATRACE_CALL();
1807 ALOGV("rebuildLayerStacks");
1808
Mathias Agopiancd60f992012-08-16 16:28:27 -07001809 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001810 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001811 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001812 mVisibleRegionsDirty = false;
1813 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001814
Jeff Sharkey76488112017-02-27 14:15:18 -07001815 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1816 Region opaqueRegion;
1817 Region dirtyRegion;
1818 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001819 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001820 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1821 const Transform& tr(displayDevice->getTransform());
1822 const Rect bounds(displayDevice->getBounds());
1823 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001824 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001825
Jeff Sharkey76488112017-02-27 14:15:18 -07001826 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001827 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001828 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1829 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001830 Region drawRegion(tr.transform(
1831 layer->visibleNonTransparentRegion));
1832 drawRegion.andSelf(bounds);
1833 if (!drawRegion.isEmpty()) {
1834 layersSortedByZ.add(layer);
1835 } else {
1836 // Clear out the HWC layer if this layer was
1837 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001838 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001839 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001840 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001841 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001842 // WM changes displayDevice->layerStack upon sleep/awake.
1843 // Here we make sure we delete the HWC layers even if
1844 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001845 hwcLayerDestroyed = layer->destroyHwcLayer(
1846 displayDevice->getHwcDisplayId());
1847 }
1848
1849 // If a layer is not going to get a release fence because
1850 // it is invisible, but it is also going to release its
1851 // old buffer, add it to the list of layers needing
1852 // fences.
1853 if (hwcLayerDestroyed) {
1854 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1855 mLayersWithQueuedFrames.cend(), layer);
1856 if (found != mLayersWithQueuedFrames.cend()) {
1857 layersNeedingFences.add(layer);
1858 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001859 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001860 });
1861 }
1862 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001863 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001864 displayDevice->undefinedRegion.set(bounds);
1865 displayDevice->undefinedRegion.subtractSelf(
1866 tr.transform(opaqueRegion));
1867 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001868 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001869 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001870}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001871
Romain Guy0147a172017-06-01 13:53:56 -07001872mat4 SurfaceFlinger::computeSaturationMatrix() const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001873 if (mGlobalSaturationFactor == 1.0f) {
Romain Guy0147a172017-06-01 13:53:56 -07001874 return mat4();
1875 }
1876
1877 // Rec.709 luma coefficients
1878 float3 luminance{0.213f, 0.715f, 0.072f};
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001879 luminance *= 1.0f - mGlobalSaturationFactor;
Romain Guy0147a172017-06-01 13:53:56 -07001880 return mat4(
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001881 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
1882 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
1883 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
Romain Guy0147a172017-06-01 13:53:56 -07001884 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1885 );
1886}
1887
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001888// Returns a dataspace that fits all visible layers. The returned dataspace
1889// can only be one of
1890//
1891// - Dataspace::V0_SRGB
1892// - Dataspace::DISPLAY_P3
1893// - Dataspace::V0_SCRGB_LINEAR
1894// TODO(b/73825729) Add BT2020 data space.
1895ui::Dataspace SurfaceFlinger::getBestDataspace(
1896 const sp<const DisplayDevice>& displayDevice) const {
1897 Dataspace bestDataspace = Dataspace::V0_SRGB;
1898 for (const auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1899 switch (layer->getDataSpace()) {
1900 case Dataspace::V0_SCRGB:
1901 case Dataspace::V0_SCRGB_LINEAR:
1902 // return immediately
1903 return Dataspace::V0_SCRGB_LINEAR;
1904 case Dataspace::BT2020_PQ:
1905 case Dataspace::BT2020_ITU_PQ:
1906 // Historically, HDR dataspaces are ignored by SurfaceFlinger. But
1907 // since SurfaceFlinger simulates HDR support now, it should honor
1908 // them unless there is also native support.
1909 if (!displayDevice->hasHdr10()) {
1910 return Dataspace::V0_SCRGB_LINEAR;
1911 }
1912 break;
1913 case Dataspace::DISPLAY_P3:
1914 bestDataspace = Dataspace::DISPLAY_P3;
1915 break;
1916 default:
1917 break;
1918 }
Romain Guy54f154a2017-10-24 21:40:32 +01001919 }
1920
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001921 return bestDataspace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001922}
1923
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001924// Pick the ColorMode / Dataspace for the display device.
1925// TODO(b/73825729) Add BT2020 color mode.
1926void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& displayDevice,
1927 ColorMode* outMode, Dataspace* outDataSpace) const {
1928 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1929 *outMode = ColorMode::NATIVE;
1930 *outDataSpace = Dataspace::UNKNOWN;
1931 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001932 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001933
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001934 switch (getBestDataspace(displayDevice)) {
1935 case Dataspace::DISPLAY_P3:
1936 case Dataspace::V0_SCRGB_LINEAR:
1937 *outMode = ColorMode::DISPLAY_P3;
1938 *outDataSpace = Dataspace::DISPLAY_P3;
1939 break;
1940 default:
1941 *outMode = ColorMode::SRGB;
1942 *outDataSpace = Dataspace::V0_SRGB;
1943 break;
1944 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001945}
1946
Mathias Agopiancd60f992012-08-16 16:28:27 -07001947void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001948 ATRACE_CALL();
1949 ALOGV("setUpHWComposer");
1950
Jesse Hall028dc8f2013-08-20 16:35:32 -07001951 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Dan Stozac7a25ad2018-04-12 11:45:09 -07001952 bool dirty = !mDisplays[dpy]->getDirtyRegion(mRepaintEverything).isEmpty();
Jesse Hallb7a05492014-08-14 15:45:06 -07001953 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1954 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1955
1956 // If nothing has changed (!dirty), don't recompose.
1957 // If something changed, but we don't currently have any visible layers,
1958 // and didn't when we last did a composition, then skip it this time.
1959 // The second rule does two things:
1960 // - When all layers are removed from a display, we'll emit one black
1961 // frame, then nothing more until we get new layers.
1962 // - When a display is created with a private layer stack, we won't
1963 // emit any black frames until a layer is added to the layer stack.
1964 bool mustRecompose = dirty && !(empty && wasEmpty);
1965
1966 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1967 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1968 mustRecompose ? "doing" : "skipping",
1969 dirty ? "+" : "-",
1970 empty ? "+" : "-",
1971 wasEmpty ? "+" : "-");
1972
Dan Stoza71433162014-02-04 16:22:36 -08001973 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001974
1975 if (mustRecompose) {
1976 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1977 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001978 }
1979
Dan Stoza9e56aa02015-11-02 13:00:03 -08001980 // build the h/w work list
1981 if (CC_UNLIKELY(mGeometryInvalid)) {
1982 mGeometryInvalid = false;
1983 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1984 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1985 const auto hwcId = displayDevice->getHwcDisplayId();
1986 if (hwcId >= 0) {
1987 const Vector<sp<Layer>>& currentLayers(
1988 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001989 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001990 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001991 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07001992 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001993 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001994 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001995 }
1996 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001997
Robert Carrae060832016-11-28 10:51:00 -08001998 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001999 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002000 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07002001 }
2002 }
2003 }
2004 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002005 }
Riley Andrews03414a12014-07-01 14:22:59 -07002006
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002007
Romain Guy0147a172017-06-01 13:53:56 -07002008 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002009
Dan Stoza9e56aa02015-11-02 13:00:03 -08002010 // Set the per-frame data
2011 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2012 auto& displayDevice = mDisplays[displayId];
2013 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002014
Dan Stoza9e56aa02015-11-02 13:00:03 -08002015 if (hwcId < 0) {
2016 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07002017 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002018 if (colorMatrix != mPreviousColorMatrix) {
Yiwei Zhang7c64f172018-03-07 14:52:28 -08002019 displayDevice->setColorTransform(colorMatrix);
David Sodman105b7dc2017-11-04 20:28:14 -07002020 status_t result = getBE().mHwc->setColorTransform(hwcId, colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002021 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
2022 "display %zd: %d", displayId, result);
2023 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002024 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002025 if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2026 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002027 !displayDevice->hasHdr10()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002028 layer->forceClientComposition(hwcId);
2029 }
2030
chaviwc9232ed2017-11-14 15:31:15 -08002031 if (layer->getForceClientComposition(hwcId)) {
2032 ALOGV("[%s] Requesting Client composition", layer->getName().string());
2033 layer->setCompositionType(hwcId, HWC2::Composition::Client);
2034 continue;
2035 }
2036
Dan Stoza9e56aa02015-11-02 13:00:03 -08002037 layer->setPerFrameData(displayDevice);
2038 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002039
2040 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002041 ColorMode colorMode;
2042 Dataspace dataSpace;
2043 pickColorMode(displayDevice, &colorMode, &dataSpace);
2044 setActiveColorModeInternal(displayDevice, colorMode, dataSpace);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002045 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002046 }
2047
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002048 mPreviousColorMatrix = colorMatrix;
2049
Dan Stoza9e56aa02015-11-02 13:00:03 -08002050 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002051 auto& displayDevice = mDisplays[displayId];
2052 if (!displayDevice->isDisplayOn()) {
2053 continue;
2054 }
2055
David Sodman105b7dc2017-11-04 20:28:14 -07002056 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002057 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2058 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002059 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002060}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002061
Mathias Agopiancd60f992012-08-16 16:28:27 -07002062void SurfaceFlinger::doComposition() {
2063 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002064 ALOGV("doComposition");
2065
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002066 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002067 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002068 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002069 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002070 // transform the dirty region into this screen's coordinate space
2071 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002072
2073 // repaint the framebuffer (if needed)
2074 doDisplayComposition(hw, dirtyRegion);
2075
Mathias Agopiancd60f992012-08-16 16:28:27 -07002076 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002077 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002078 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002079 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002080 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002081}
2082
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002083void SurfaceFlinger::postFramebuffer()
2084{
Mathias Agopian841cde52012-03-01 15:44:37 -08002085 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002086 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002087
Mathias Agopiana44b0412011-10-16 18:46:35 -07002088 const nsecs_t now = systemTime();
2089 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002090
Dan Stoza9e56aa02015-11-02 13:00:03 -08002091 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2092 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002093 if (!displayDevice->isDisplayOn()) {
2094 continue;
2095 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002096 const auto hwcId = displayDevice->getHwcDisplayId();
2097 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002098 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002099 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002100 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002101 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002102 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002103 // The layer buffer from the previous frame (if any) is released
2104 // by HWC only when the release fence from this frame (if any) is
2105 // signaled. Always get the release fence from HWC first.
2106 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002107 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002108
2109 // If the layer was client composited in the previous frame, we
2110 // need to merge with the previous client target acquire fence.
2111 // Since we do not track that, always merge with the current
2112 // client target acquire fence when it is available, even though
2113 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002114 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002115 releaseFence = Fence::merge("LayerRelease", releaseFence,
2116 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002117 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002118
Dan Stoza9e56aa02015-11-02 13:00:03 -08002119 layer->onLayerDisplayed(releaseFence);
2120 }
Chia-I Wu83806892017-11-16 10:50:20 -08002121
2122 // We've got a list of layers needing fences, that are disjoint with
2123 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2124 // supply them with the present fence.
2125 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002126 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002127 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2128 layer->onLayerDisplayed(presentFence);
2129 }
2130 }
2131
Dan Stoza9e56aa02015-11-02 13:00:03 -08002132 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002133 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002134 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002135 }
2136
Mathias Agopiana44b0412011-10-16 18:46:35 -07002137 mLastSwapBufferTime = systemTime() - now;
2138 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002139
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002140 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002141 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2142 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2143 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2144 logFrameStats();
2145 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002146 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002147}
2148
Mathias Agopian87baae12012-07-31 12:38:26 -07002149void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002150{
Mathias Agopian841cde52012-03-01 15:44:37 -08002151 ATRACE_CALL();
2152
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002153 // here we keep a copy of the drawing state (that is the state that's
2154 // going to be overwritten by handleTransactionLocked()) outside of
2155 // mStateLock so that the side-effects of the State assignment
2156 // don't happen with mStateLock held (which can cause deadlocks).
2157 State drawingState(mDrawingState);
2158
Mathias Agopianca4d3602011-05-19 15:38:14 -07002159 Mutex::Autolock _l(mStateLock);
2160 const nsecs_t now = systemTime();
2161 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002162
Mathias Agopianca4d3602011-05-19 15:38:14 -07002163 // Here we're guaranteed that some transaction flags are set
2164 // so we can call handleTransactionLocked() unconditionally.
2165 // We call getTransactionFlags(), which will also clear the flags,
2166 // with mStateLock held to guarantee that mCurrentState won't change
2167 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002168
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002169 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002170 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002171 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002172
Mathias Agopianca4d3602011-05-19 15:38:14 -07002173 mLastTransactionTime = systemTime() - now;
2174 mDebugInTransaction = 0;
2175 invalidateHwcGeometry();
2176 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002177}
2178
Lloyd Pique715a2c12017-12-14 17:18:08 -08002179DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique09594832018-01-22 17:48:03 -08002180 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002181 // Figure out whether the event is for the primary display or an
2182 // external display by matching the Hwc display id against one for a
2183 // connected display. If we did not find a match, we then check what
2184 // displays are not already connected to determine the type. If we don't
2185 // have a connected primary display, we assume the new display is meant to
2186 // be the primary display, and then if we don't have an external display,
2187 // we assume it is that.
2188 const auto primaryDisplayId =
2189 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2190 const auto externalDisplayId =
2191 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2192 if (primaryDisplayId && primaryDisplayId == display) {
2193 return DisplayDevice::DISPLAY_PRIMARY;
2194 } else if (externalDisplayId && externalDisplayId == display) {
2195 return DisplayDevice::DISPLAY_EXTERNAL;
2196 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2197 return DisplayDevice::DISPLAY_PRIMARY;
2198 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2199 return DisplayDevice::DISPLAY_EXTERNAL;
2200 }
2201
2202 return DisplayDevice::DISPLAY_ID_INVALID;
2203}
2204
Lloyd Piqueba04e622017-12-14 17:11:26 -08002205void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2206 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002207 auto displayType = determineDisplayType(event.display, event.connection);
2208 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2209 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2210 continue;
2211 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002212
2213 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2214 ALOGE("External displays are not supported by the vr hardware composer.");
2215 continue;
2216 }
2217
Lloyd Pique715a2c12017-12-14 17:18:08 -08002218 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002219
2220 if (event.connection == HWC2::Connection::Connected) {
Steven Thomas3bed0522018-03-20 15:40:48 -07002221 if (!mBuiltinDisplays[displayType].get()) {
2222 ALOGV("Creating built in display %d", displayType);
2223 mBuiltinDisplays[displayType] = new BBinder();
2224 // All non-virtual displays are currently considered secure.
2225 DisplayDeviceState info(displayType, true);
2226 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2227 "Built-in Screen" : "External Screen";
2228 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
Lloyd Pique4d234852018-01-22 17:21:36 -08002229 mInterceptor->saveDisplayCreation(info);
Steven Thomas3bed0522018-03-20 15:40:48 -07002230 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002231 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002232 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002233
Lloyd Piquefcd86612017-12-14 17:15:36 -08002234 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2235 if (idx >= 0) {
2236 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Lloyd Pique4d234852018-01-22 17:21:36 -08002237 mInterceptor->saveDisplayDeletion(info.displayId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002238 mCurrentState.displays.removeItemsAt(idx);
2239 }
2240 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002241 }
2242
2243 processDisplayChangesLocked();
2244 }
2245
2246 mPendingHotplugEvents.clear();
2247}
2248
Lloyd Pique09594832018-01-22 17:48:03 -08002249sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2250 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2251 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002252 bool hasWideColorGamut = false;
Lloyd Pique09594832018-01-22 17:48:03 -08002253 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002254 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Lloyd Pique09594832018-01-22 17:48:03 -08002255 for (ColorMode colorMode : modes) {
2256 switch (colorMode) {
2257 case ColorMode::DISPLAY_P3:
2258 case ColorMode::ADOBE_RGB:
2259 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002260 hasWideColorGamut = true;
Lloyd Pique09594832018-01-22 17:48:03 -08002261 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002262 // TODO(lpy) Handle BT2020, BT2100_PQ and BT2100_HLG properly.
Lloyd Pique09594832018-01-22 17:48:03 -08002263 default:
2264 break;
2265 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002266
2267 std::vector<RenderIntent> renderIntents = getHwComposer().getRenderIntents(hwcId,
2268 colorMode);
2269 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2270 for (auto intent : renderIntents) {
2271 if (intent == RenderIntent::ENHANCE) {
2272 mBuiltinDisplaySupportsEnhance = true;
2273 break;
2274 }
2275 }
2276 }
Lloyd Pique09594832018-01-22 17:48:03 -08002277 }
2278 }
2279
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002280 bool hasHdr10 = false;
2281 std::unique_ptr<HdrCapabilities> hdrCapabilities = getHwComposer().getHdrCapabilities(hwcId);
Lloyd Pique09594832018-01-22 17:48:03 -08002282 if (hdrCapabilities) {
2283 const std::vector<int32_t> types = hdrCapabilities->getSupportedHdrTypes();
2284 auto iter = std::find(types.cbegin(), types.cend(), HAL_HDR_HDR10);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002285 hasHdr10 = iter != types.cend();
Lloyd Pique09594832018-01-22 17:48:03 -08002286 }
2287
2288 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2289 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2290
2291 /*
2292 * Create our display's surface
2293 */
2294 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2295 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
2296 renderSurface->setAsync(state.type >= DisplayDevice::DISPLAY_VIRTUAL);
2297 renderSurface->setNativeWindow(nativeWindow.get());
2298 const int displayWidth = renderSurface->queryWidth();
2299 const int displayHeight = renderSurface->queryHeight();
2300
2301 // Make sure that composition can never be stalled by a virtual display
2302 // consumer that isn't processing buffers fast enough. We have to do this
2303 // in two places:
2304 // * Here, in case the display is composed entirely by HWC.
2305 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2306 // window's swap interval in eglMakeCurrent, so they'll override the
2307 // interval we set here.
2308 if (state.type >= DisplayDevice::DISPLAY_VIRTUAL) {
2309 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2310 }
2311
2312 // virtual displays are always considered enabled
2313 auto initialPowerMode = (state.type >= DisplayDevice::DISPLAY_VIRTUAL) ? HWC_POWER_MODE_NORMAL
2314 : HWC_POWER_MODE_OFF;
2315
2316 sp<DisplayDevice> hw =
2317 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2318 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002319 hasWideColorGamut, hasHdr10, initialPowerMode);
Lloyd Pique09594832018-01-22 17:48:03 -08002320
2321 if (maxFrameBufferAcquiredBuffers >= 3) {
2322 nativeWindowSurface->preallocateBuffers();
2323 }
2324
2325 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002326 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2327 if (hasWideColorGamut) {
Lloyd Pique09594832018-01-22 17:48:03 -08002328 defaultColorMode = ColorMode::SRGB;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002329 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique09594832018-01-22 17:48:03 -08002330 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002331 setActiveColorModeInternal(hw, defaultColorMode, defaultDataSpace);
Lloyd Pique09594832018-01-22 17:48:03 -08002332 hw->setLayerStack(state.layerStack);
2333 hw->setProjection(state.orientation, state.viewport, state.frame);
2334 hw->setDisplayName(state.displayName);
2335
2336 return hw;
2337}
2338
Lloyd Pique347200f2017-12-14 17:00:15 -08002339void SurfaceFlinger::processDisplayChangesLocked() {
2340 // here we take advantage of Vector's copy-on-write semantics to
2341 // improve performance by skipping the transaction entirely when
2342 // know that the lists are identical
2343 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2344 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2345 if (!curr.isIdenticalTo(draw)) {
2346 mVisibleRegionsDirty = true;
2347 const size_t cc = curr.size();
2348 size_t dc = draw.size();
2349
2350 // find the displays that were removed
2351 // (ie: in drawing state but not in current state)
2352 // also handle displays that changed
2353 // (ie: displays that are in both lists)
2354 for (size_t i = 0; i < dc;) {
2355 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2356 if (j < 0) {
2357 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002358 // Call makeCurrent() on the primary display so we can
2359 // be sure that nothing associated with this display
2360 // is current.
2361 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2362 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2363 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2364 if (hw != nullptr) hw->disconnect(getHwComposer());
2365 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2366 mEventThread->onHotplugReceived(draw[i].type, false);
2367 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002368 } else {
2369 // this display is in both lists. see if something changed.
2370 const DisplayDeviceState& state(curr[j]);
2371 const wp<IBinder>& display(curr.keyAt(j));
2372 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2373 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2374 if (state_binder != draw_binder) {
2375 // changing the surface is like destroying and
2376 // recreating the DisplayDevice, so we just remove it
2377 // from the drawing state, so that it get re-added
2378 // below.
2379 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2380 if (hw != nullptr) hw->disconnect(getHwComposer());
2381 mDisplays.removeItem(display);
2382 mDrawingState.displays.removeItemsAt(i);
2383 dc--;
2384 // at this point we must loop to the next item
2385 continue;
2386 }
2387
2388 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2389 if (disp != nullptr) {
2390 if (state.layerStack != draw[i].layerStack) {
2391 disp->setLayerStack(state.layerStack);
2392 }
2393 if ((state.orientation != draw[i].orientation) ||
2394 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2395 disp->setProjection(state.orientation, state.viewport, state.frame);
2396 }
2397 if (state.width != draw[i].width || state.height != draw[i].height) {
2398 disp->setDisplaySize(state.width, state.height);
2399 }
2400 }
2401 }
2402 ++i;
2403 }
2404
2405 // find displays that were added
2406 // (ie: in current state but not in drawing state)
2407 for (size_t i = 0; i < cc; i++) {
2408 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2409 const DisplayDeviceState& state(curr[i]);
2410
2411 sp<DisplaySurface> dispSurface;
2412 sp<IGraphicBufferProducer> producer;
2413 sp<IGraphicBufferProducer> bqProducer;
2414 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002415 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002416
2417 int32_t hwcId = -1;
2418 if (state.isVirtualDisplay()) {
2419 // Virtual displays without a surface are dormant:
2420 // they have external state (layer stack, projection,
2421 // etc.) but no internal state (i.e. a DisplayDevice).
2422 if (state.surface != nullptr) {
2423 // Allow VR composer to use virtual displays.
2424 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2425 int width = 0;
2426 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2427 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2428 int height = 0;
2429 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2430 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2431 int intFormat = 0;
2432 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2433 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002434 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002435
2436 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2437 }
2438
2439 // TODO: Plumb requested format back up to consumer
2440
2441 sp<VirtualDisplaySurface> vds =
2442 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2443 bqProducer, bqConsumer,
2444 state.displayName);
2445
2446 dispSurface = vds;
2447 producer = vds;
2448 }
2449 } else {
2450 ALOGE_IF(state.surface != nullptr,
2451 "adding a supported display, but rendering "
2452 "surface is provided (%p), ignoring it",
2453 state.surface.get());
2454
2455 hwcId = state.type;
2456 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2457 producer = bqProducer;
2458 }
2459
2460 const wp<IBinder>& display(curr.keyAt(i));
2461 if (dispSurface != nullptr) {
Lloyd Pique09594832018-01-22 17:48:03 -08002462 mDisplays.add(display,
2463 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2464 producer));
Lloyd Pique347200f2017-12-14 17:00:15 -08002465 if (!state.isVirtualDisplay()) {
2466 mEventThread->onHotplugReceived(state.type, true);
2467 }
2468 }
2469 }
2470 }
2471 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002472
2473 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002474}
2475
Mathias Agopian87baae12012-07-31 12:38:26 -07002476void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002477{
Dan Stoza7dde5992015-05-22 09:51:44 -07002478 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002479 mCurrentState.traverseInZOrder([](Layer* layer) {
2480 layer->notifyAvailableFrames();
2481 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002482
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002483 /*
2484 * Traversal of the children
2485 * (perform the transaction for each of them if needed)
2486 */
2487
Mathias Agopian3559b072012-08-15 13:46:03 -07002488 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002489 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002490 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002491 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002492
2493 const uint32_t flags = layer->doTransaction(0);
2494 if (flags & Layer::eVisibleRegion)
2495 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002496 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002497 }
2498
2499 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002500 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002501 */
2502
Mathias Agopiane57f2922012-08-09 16:29:12 -07002503 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002504 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002505 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002506 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002507
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002508 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002509 // The transform hint might have changed for some layers
2510 // (either because a display has changed, or because a layer
2511 // as changed).
2512 //
2513 // Walk through all the layers in currentLayers,
2514 // and update their transform hint.
2515 //
2516 // If a layer is visible only on a single display, then that
2517 // display is used to calculate the hint, otherwise we use the
2518 // default display.
2519 //
2520 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2521 // the hint is set before we acquire a buffer from the surface texture.
2522 //
2523 // NOTE: layer transactions have taken place already, so we use their
2524 // drawing state. However, SurfaceFlinger's own transaction has not
2525 // happened yet, so we must use the current state layer list
2526 // (soon to become the drawing state list).
2527 //
2528 sp<const DisplayDevice> disp;
2529 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002530 bool first = true;
2531 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002532 // NOTE: we rely on the fact that layers are sorted by
2533 // layerStack first (so we don't have to traverse the list
2534 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002535 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002536 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002537 currentlayerStack = layerStack;
2538 // figure out if this layerstack is mirrored
2539 // (more than one display) if so, pick the default display,
2540 // if not, pick the only display it's on.
2541 disp.clear();
2542 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2543 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002544 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002545 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002546 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002547 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002548 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002549 break;
2550 }
2551 }
2552 }
2553 }
Chet Haase91d25932013-04-11 15:24:55 -07002554
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002555 if (disp == nullptr) {
2556 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2557 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002558
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002559 // could be null when this layer is using a layerStack
2560 // that is not visible on any display. Also can occur at
2561 // screen off/on times.
2562 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002563 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002564
2565 // disp can be null if there is no display available at all to get
2566 // the transform hint from.
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002567 if (disp != nullptr) {
2568 layer->updateTransformHint(disp);
2569 }
Robert Carr2047fae2016-11-28 14:09:09 -08002570
2571 first = false;
2572 });
Mathias Agopian84300952012-11-21 16:02:13 -08002573 }
2574
2575
Mathias Agopian3559b072012-08-15 13:46:03 -07002576 /*
2577 * Perform our own transaction if needed
2578 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002579
2580 if (mLayersAdded) {
2581 mLayersAdded = false;
2582 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002583 mVisibleRegionsDirty = true;
2584 }
2585
2586 // some layers might have been removed, so
2587 // we need to update the regions they're exposing.
2588 if (mLayersRemoved) {
2589 mLayersRemoved = false;
2590 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002591 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002592 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002593 // this layer is not visible anymore
2594 // TODO: we could traverse the tree from front to back and
2595 // compute the actual visible region
2596 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002597 Region visibleReg;
2598 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002599 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002600 }
Robert Carr2047fae2016-11-28 14:09:09 -08002601 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002602 }
2603
2604 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002605
2606 updateCursorAsync();
2607}
2608
2609void SurfaceFlinger::updateCursorAsync()
2610{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002611 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2612 auto& displayDevice = mDisplays[displayId];
2613 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002614 continue;
2615 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002616
2617 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2618 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002619 }
2620 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002621}
2622
2623void SurfaceFlinger::commitTransaction()
2624{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002625 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002626 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002627 for (const auto& l : mLayersPendingRemoval) {
2628 recordBufferingStats(l->getName().string(),
2629 l->getOccupancyHistory(true));
2630 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002631 }
2632 mLayersPendingRemoval.clear();
2633 }
2634
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002635 // If this transaction is part of a window animation then the next frame
2636 // we composite should be considered an animation as well.
2637 mAnimCompositionPending = mAnimTransactionPending;
2638
Mathias Agopian4fec8732012-06-29 14:12:52 -07002639 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002640 mDrawingState.traverseInZOrder([](Layer* layer) {
2641 layer->commitChildList();
2642 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002643 mTransactionPending = false;
2644 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002645 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002646}
2647
Chia-I Wuab0c3192017-08-01 11:29:00 -07002648void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002649 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002650{
Mathias Agopian841cde52012-03-01 15:44:37 -08002651 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002652 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002653
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002654 Region aboveOpaqueLayers;
2655 Region aboveCoveredLayers;
2656 Region dirty;
2657
Mathias Agopian87baae12012-07-31 12:38:26 -07002658 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002659
Robert Carr2047fae2016-11-28 14:09:09 -08002660 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002661 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002662 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002663
Jesse Hall01e29052013-02-19 16:13:35 -08002664 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002665 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002666 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002667
Mathias Agopianab028732010-03-16 16:41:46 -07002668 /*
2669 * opaqueRegion: area of a surface that is fully opaque.
2670 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002671 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002672
2673 /*
2674 * visibleRegion: area of a surface that is visible on screen
2675 * and not fully transparent. This is essentially the layer's
2676 * footprint minus the opaque regions above it.
2677 * Areas covered by a translucent surface are considered visible.
2678 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002679 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002680
2681 /*
2682 * coveredRegion: area of a surface that is covered by all
2683 * visible regions above it (which includes the translucent areas).
2684 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002685 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002686
Jesse Halla8026d22012-09-25 13:25:04 -07002687 /*
2688 * transparentRegion: area of a surface that is hinted to be completely
2689 * transparent. This is only used to tell when the layer has no visible
2690 * non-transparent regions and can be removed from the layer list. It
2691 * does not affect the visibleRegion of this layer or any layers
2692 * beneath it. The hint may not be correct if apps don't respect the
2693 * SurfaceView restrictions (which, sadly, some don't).
2694 */
2695 Region transparentRegion;
2696
Mathias Agopianab028732010-03-16 16:41:46 -07002697
2698 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002699 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002700 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002701 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002702 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002703 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002704 if (!visibleRegion.isEmpty()) {
2705 // Remove the transparent area from the visible region
2706 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002707 if (tr.preserveRects()) {
2708 // transform the transparent region
2709 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002710 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002711 // transformation too complex, can't do the
2712 // transparent region optimization.
2713 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002714 }
Mathias Agopianab028732010-03-16 16:41:46 -07002715 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002716
Mathias Agopianab028732010-03-16 16:41:46 -07002717 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002718 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002719 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002720 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2721 // the opaque region is the layer's footprint
2722 opaqueRegion = visibleRegion;
2723 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002724 }
2725 }
2726
Robert Carre5f4f692018-01-12 13:12:28 -08002727 if (visibleRegion.isEmpty()) {
2728 layer->clearVisibilityRegions();
2729 return;
2730 }
2731
Mathias Agopianab028732010-03-16 16:41:46 -07002732 // Clip the covered region to the visible region
2733 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2734
2735 // Update aboveCoveredLayers for next (lower) layer
2736 aboveCoveredLayers.orSelf(visibleRegion);
2737
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002738 // subtract the opaque region covered by the layers above us
2739 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002740
2741 // compute this layer's dirty region
2742 if (layer->contentDirty) {
2743 // we need to invalidate the whole region
2744 dirty = visibleRegion;
2745 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002746 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002747 layer->contentDirty = false;
2748 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002749 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002750 * the exposed region consists of two components:
2751 * 1) what's VISIBLE now and was COVERED before
2752 * 2) what's EXPOSED now less what was EXPOSED before
2753 *
2754 * note that (1) is conservative, we start with the whole
2755 * visible region but only keep what used to be covered by
2756 * something -- which mean it may have been exposed.
2757 *
2758 * (2) handles areas that were not covered by anything but got
2759 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002760 */
Mathias Agopianab028732010-03-16 16:41:46 -07002761 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002762 const Region oldVisibleRegion = layer->visibleRegion;
2763 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002764 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2765 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002766 }
2767 dirty.subtractSelf(aboveOpaqueLayers);
2768
2769 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002770 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002771
Mathias Agopianab028732010-03-16 16:41:46 -07002772 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002773 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002774
Jesse Halla8026d22012-09-25 13:25:04 -07002775 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002776 layer->setVisibleRegion(visibleRegion);
2777 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002778 layer->setVisibleNonTransparentRegion(
2779 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002780 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002781
Mathias Agopian87baae12012-07-31 12:38:26 -07002782 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002783}
2784
Chia-I Wuab0c3192017-08-01 11:29:00 -07002785void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002786 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002787 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002788 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002789 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002790 }
2791 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002792}
2793
Dan Stoza6b9454d2014-11-07 16:00:59 -08002794bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002795{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002796 ALOGV("handlePageFlip");
2797
Brian Andersond6927fb2016-07-23 23:37:30 -07002798 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002799
Mathias Agopian4fec8732012-06-29 14:12:52 -07002800 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002801 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002802 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002803
2804 // Store the set of layers that need updates. This set must not change as
2805 // buffers are being latched, as this could result in a deadlock.
2806 // Example: Two producers share the same command stream and:
2807 // 1.) Layer 0 is latched
2808 // 2.) Layer 0 gets a new frame
2809 // 2.) Layer 1 gets a new frame
2810 // 3.) Layer 1 is latched.
2811 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2812 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002813 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002814 if (layer->hasQueuedFrame()) {
2815 frameQueued = true;
2816 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002817 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002818 } else {
2819 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002820 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002821 } else {
2822 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002823 }
Robert Carr2047fae2016-11-28 14:09:09 -08002824 });
2825
Dan Stoza9e56aa02015-11-02 13:00:03 -08002826 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002827 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002828 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002829 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002830 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002831 newDataLatched = true;
2832 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002833 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002834
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002835 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002836
2837 // If we will need to wake up at some time in the future to deal with a
2838 // queued frame that shouldn't be displayed during this vsync period, wake
2839 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002840 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002841 signalLayerUpdate();
2842 }
2843
2844 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002845 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002846}
2847
Mathias Agopianad456f92011-01-13 17:53:01 -08002848void SurfaceFlinger::invalidateHwcGeometry()
2849{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002850 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002851}
2852
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002853
Fabien Sanglard830b8472016-11-30 16:35:58 -08002854void SurfaceFlinger::doDisplayComposition(
2855 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002856 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002857{
Dan Stoza71433162014-02-04 16:22:36 -08002858 // We only need to actually compose the display if:
2859 // 1) It is being handled by hardware composer, which may need this to
2860 // keep its virtual display state machine in sync, or
2861 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002862 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002863 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002864 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002865 return;
2866 }
2867
Dan Stoza9e56aa02015-11-02 13:00:03 -08002868 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002869 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002870
2871 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002872 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002873}
2874
Chia-I Wub02087d2017-11-09 10:19:54 -08002875bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002876{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002877 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002878
Chia-I Wub02087d2017-11-09 10:19:54 -08002879 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002880 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002881 const auto hwcId = displayDevice->getHwcDisplayId();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002882 const bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
2883 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
2884 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2885 HWC2::Capability::SkipClientColorTransform);
2886 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002887
2888 mat4 oldColorMatrix;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002889 mat4 legacySrgbSaturationMatrix = mLegacySrgbSaturationMatrix;
2890 const bool applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002891 if (applyColorMatrix) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002892 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002893 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002894 legacySrgbSaturationMatrix = colorMatrix * legacySrgbSaturationMatrix;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002895 }
2896
Dan Stoza9e56aa02015-11-02 13:00:03 -08002897 if (hasClientComposition) {
2898 ALOGV("hasClientComposition");
2899
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002900 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002901 if (displayDevice->hasWideColorGamut()) {
2902 outputDataspace = displayDevice->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002903 }
2904 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
2905
Chia-I Wu7f402902017-11-09 12:51:10 -08002906 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002907 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002908 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002909 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002910
2911 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002912 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002913 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2914 }
2915 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002916 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002917
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002918 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002919 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002920 // when using overlays, we assume a fully transparent framebuffer
2921 // NOTE: we could reduce how much we need to clear, for instance
2922 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002923 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002924 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002925 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002926 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002927 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002928 // we're left with the letterbox region
2929 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002930 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002931
2932 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002933 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002934
Mathias Agopianb9494d52012-04-18 02:28:45 -07002935 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002936 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002937 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002938 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002939 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002940 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002941
Dan Stoza9e56aa02015-11-02 13:00:03 -08002942 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002943 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002944 // scissor on the main display. It should never be needed
2945 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002946 const Rect& bounds(displayDevice->getBounds());
2947 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002948 if (scissor != bounds) {
2949 // scissor doesn't match the screen's dimensions, so we
2950 // need to clear everything outside of it and enable
2951 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002952
Mathias Agopianf45c5102012-10-24 16:29:17 -07002953 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002954 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002955 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002956 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002957 }
2958 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002959 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002960
Mathias Agopian85d751c2012-08-29 16:59:24 -07002961 /*
2962 * and then, render the layers targeted at the framebuffer
2963 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002964
Dan Stoza9e56aa02015-11-02 13:00:03 -08002965 ALOGV("Rendering client layers");
2966 const Transform& displayTransform = displayDevice->getTransform();
2967 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002968 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002969 bool firstLayer = true;
2970 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08002971 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002972 displayTransform.transform(layer->visibleRegion)));
2973 ALOGV("Layer: %s", layer->getName().string());
2974 ALOGV(" Composition type: %s",
2975 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002976 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002977 switch (layer->getCompositionType(hwcId)) {
2978 case HWC2::Composition::Cursor:
2979 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002980 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002981 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002982 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002983 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
chaviw13fdc492017-06-27 12:40:18 -07002984 layer->isOpaque(state) && (state.color.a == 1.0f)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002985 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002986 // never clear the very first layer since we're
2987 // guaranteed the FB is already cleared
chaviwa76b2712017-09-20 12:02:26 -07002988 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002989 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002990 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002991 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002992 case HWC2::Composition::Client: {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002993 // Only apply saturation matrix layer that is legacy SRGB dataspace
2994 // when auto color mode is on.
2995 bool restore = false;
2996 mat4 savedMatrix;
2997 if (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
2998 layer->isLegacySrgbDataSpace()) {
2999 savedMatrix =
3000 getRenderEngine().setupColorTransform(legacySrgbSaturationMatrix);
3001 restore = true;
3002 }
chaviwa76b2712017-09-20 12:02:26 -07003003 layer->draw(renderArea, clip);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003004 if (restore) {
3005 getRenderEngine().setupColorTransform(savedMatrix);
3006 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003007 break;
3008 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003009 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07003010 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003011 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003012 } else {
3013 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003014 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003015 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003016 }
3017 } else {
3018 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08003019 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wub02087d2017-11-09 10:19:54 -08003020 const Region clip(bounds.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08003021 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07003022 if (!clip.isEmpty()) {
chaviwa76b2712017-09-20 12:02:26 -07003023 layer->draw(renderArea, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07003024 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003025 }
3026 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003027
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003028 if (applyColorMatrix) {
3029 getRenderEngine().setupColorTransform(oldColorMatrix);
3030 }
3031
Mathias Agopianf45c5102012-10-24 16:29:17 -07003032 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003033 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003034 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003035}
3036
Fabien Sanglard830b8472016-11-30 16:35:58 -08003037void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
3038 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003039 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003040 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003041}
3042
Dan Stoza7d89d062015-04-30 13:29:25 -07003043status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003044 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003045 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003046 const sp<Layer>& lbc,
3047 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003048{
Dan Stoza7d89d062015-04-30 13:29:25 -07003049 // add this layer to the current state list
3050 {
3051 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003052 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003053 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3054 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003055 return NO_MEMORY;
3056 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003057 if (parent == nullptr) {
3058 mCurrentState.layersSortedByZ.add(lbc);
3059 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003060 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003061 ALOGE("addClientLayer called with a removed parent");
3062 return NAME_NOT_FOUND;
3063 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003064 parent->addChild(lbc);
3065 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003066
Dan Stoza101d8dc2018-02-27 15:42:25 -08003067 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
Dan Stoza0a0158c2018-03-16 13:38:54 -07003068 // TODO (b/74616334): Change this back to a fatal assert once the leak is fixed
3069 ALOGE_IF(mGraphicBufferProducerList.size() > mMaxGraphicBufferProducerListSize,
3070 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3071 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize,
3072 mNumLayers);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003073 mLayersAdded = true;
3074 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003075 }
3076
Mathias Agopian96f08192010-06-02 23:28:45 -07003077 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003078 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003079
Dan Stoza7d89d062015-04-30 13:29:25 -07003080 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003081}
3082
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003083status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003084 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003085 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3086}
Robert Carr7f9b8992017-03-10 11:08:39 -08003087
chaviwca27f252018-02-06 16:46:39 -08003088status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3089 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003090 if (layer->isPendingRemoval()) {
3091 return NO_ERROR;
3092 }
3093
Robert Carr1f0a16a2016-10-24 16:27:39 -07003094 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003095 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003096 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003097 if (topLevelOnly) {
3098 return NO_ERROR;
3099 }
3100
Chia-I Wu98f1c102017-05-30 14:54:08 -07003101 sp<Layer> ancestor = p;
3102 while (ancestor->getParent() != nullptr) {
3103 ancestor = ancestor->getParent();
3104 }
3105 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3106 ALOGE("removeLayer called with a layer whose parent has been removed");
3107 return NAME_NOT_FOUND;
3108 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003109
3110 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003111 } else {
3112 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003113 }
3114
Robert Carr136e2f62017-02-08 17:54:29 -08003115 // As a matter of normal operation, the LayerCleaner will produce a second
3116 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3117 // so we will succeed in promoting it, but it's already been removed
3118 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3119 // otherwise something has gone wrong and we are leaking the layer.
3120 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003121 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3122 layer->getName().string(),
3123 (p != nullptr) ? p->getName().string() : "no-parent");
3124 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003125 } else if (index < 0) {
3126 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003127 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003128
Chia-I Wuc6657022017-08-15 11:18:17 -07003129 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003130 mLayersPendingRemoval.add(layer);
3131 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003132 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003133 setTransactionFlags(eTransactionNeeded);
3134 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003135}
3136
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003137uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003138 return android_atomic_release_load(&mTransactionFlags);
3139}
3140
Mathias Agopian3f844832013-08-07 21:24:32 -07003141uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003142 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3143}
3144
Mathias Agopian3f844832013-08-07 21:24:32 -07003145uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza2713c302018-03-28 17:07:36 -07003146 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3147}
3148
3149uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3150 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003151 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza2713c302018-03-28 17:07:36 -07003152 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003153 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003154 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003155 }
3156 return old;
3157}
3158
chaviwca27f252018-02-06 16:46:39 -08003159bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3160 for (const ComposerState& state : states) {
3161 // Here we need to check that the interface we're given is indeed
3162 // one of our own. A malicious client could give us a nullptr
3163 // IInterface, or one of its own or even one of our own but a
3164 // different type. All these situations would cause us to crash.
3165 if (state.client == nullptr) {
3166 return true;
3167 }
3168
3169 sp<IBinder> binder = IInterface::asBinder(state.client);
3170 if (binder == nullptr) {
3171 return true;
3172 }
3173
3174 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3175 return true;
3176 }
3177 }
3178 return false;
3179}
3180
Mathias Agopian8b33f032012-07-24 20:43:54 -07003181void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003182 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003183 const Vector<DisplayState>& displays,
3184 uint32_t flags)
3185{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003186 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003187 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003188 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003189
chaviwca27f252018-02-06 16:46:39 -08003190 if (containsAnyInvalidClientState(states)) {
3191 return;
3192 }
3193
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003194 if (flags & eAnimation) {
3195 // For window updates that are part of an animation we must wait for
3196 // previous animation "frames" to be handled.
3197 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003198 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003199 if (CC_UNLIKELY(err != NO_ERROR)) {
3200 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003201 // caller after a few seconds.
3202 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3203 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003204 mAnimTransactionPending = false;
3205 break;
3206 }
3207 }
3208 }
3209
chaviwca27f252018-02-06 16:46:39 -08003210 for (const DisplayState& display : displays) {
3211 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003212 }
3213
chaviwca27f252018-02-06 16:46:39 -08003214 for (const ComposerState& state : states) {
3215 transactionFlags |= setClientStateLocked(state);
3216 }
3217
3218 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3219 // as destroyed should only occur after setting all other states. This is to allow for a
3220 // child re-parent to happen before marking its original parent as destroyed (which would
3221 // then mark the child as destroyed).
3222 for (const ComposerState& state : states) {
3223 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003224 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003225
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003226 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3227 // anyway. This can be used as a flush mechanism for previous async transactions.
3228 // Empty animation transaction can be used to simulate back-pressure, so also force a
3229 // transaction for empty animation transactions.
3230 if (transactionFlags == 0 &&
3231 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003232 transactionFlags = eTransactionNeeded;
3233 }
3234
Mathias Agopian386aa982011-11-07 21:58:03 -08003235 if (transactionFlags) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003236 if (mInterceptor->isEnabled()) {
3237 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003238 }
Irvel468051e2016-06-13 16:44:44 -07003239
Mathias Agopian386aa982011-11-07 21:58:03 -08003240 // this triggers the transaction
Dan Stoza2713c302018-03-28 17:07:36 -07003241 const auto start = (flags & eEarlyWakeup)
3242 ? VSyncModulator::TransactionStart::EARLY
3243 : VSyncModulator::TransactionStart::NORMAL;
3244 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003245
3246 // if this is a synchronous transaction, wait for it to take effect
3247 // before returning.
3248 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003249 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003250 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003251 if (flags & eAnimation) {
3252 mAnimTransactionPending = true;
3253 }
3254 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003255 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3256 if (CC_UNLIKELY(err != NO_ERROR)) {
3257 // just in case something goes wrong in SF, return to the
3258 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003259 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3260 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003261 break;
3262 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003263 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003264 }
3265}
3266
Mathias Agopiane57f2922012-08-09 16:29:12 -07003267uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3268{
Jesse Hall9a143922012-10-04 16:29:19 -07003269 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3270 if (dpyIdx < 0)
3271 return 0;
3272
Mathias Agopiane57f2922012-08-09 16:29:12 -07003273 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003274 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003275 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003276 const uint32_t what = s.what;
3277 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003278 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003279 disp.surface = s.surface;
3280 flags |= eDisplayTransactionNeeded;
3281 }
3282 }
3283 if (what & DisplayState::eLayerStackChanged) {
3284 if (disp.layerStack != s.layerStack) {
3285 disp.layerStack = s.layerStack;
3286 flags |= eDisplayTransactionNeeded;
3287 }
3288 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003289 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003290 if (disp.orientation != s.orientation) {
3291 disp.orientation = s.orientation;
3292 flags |= eDisplayTransactionNeeded;
3293 }
3294 if (disp.frame != s.frame) {
3295 disp.frame = s.frame;
3296 flags |= eDisplayTransactionNeeded;
3297 }
3298 if (disp.viewport != s.viewport) {
3299 disp.viewport = s.viewport;
3300 flags |= eDisplayTransactionNeeded;
3301 }
3302 }
Michael Lentine47e45402014-07-18 15:34:25 -07003303 if (what & DisplayState::eDisplaySizeChanged) {
3304 if (disp.width != s.width) {
3305 disp.width = s.width;
3306 flags |= eDisplayTransactionNeeded;
3307 }
3308 if (disp.height != s.height) {
3309 disp.height = s.height;
3310 flags |= eDisplayTransactionNeeded;
3311 }
3312 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003313 }
3314 return flags;
3315}
3316
chaviwca27f252018-02-06 16:46:39 -08003317uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3318 const layer_state_t& s = composerState.state;
3319 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3320
Mathias Agopian13127d82013-03-05 17:47:11 -08003321 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003322 if (layer == nullptr) {
3323 return 0;
3324 }
3325
3326 if (layer->isPendingRemoval()) {
3327 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3328 return 0;
3329 }
3330
3331 uint32_t flags = 0;
3332
3333 const uint32_t what = s.what;
3334 bool geometryAppliesWithResize =
3335 what & layer_state_t::eGeometryAppliesWithResize;
3336 if (what & layer_state_t::ePositionChanged) {
3337 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3338 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003339 }
chaviw8b3871a2017-11-01 17:41:01 -07003340 }
3341 if (what & layer_state_t::eLayerChanged) {
3342 // NOTE: index needs to be calculated before we update the state
3343 const auto& p = layer->getParent();
3344 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003345 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003346 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003347 mCurrentState.layersSortedByZ.removeAt(idx);
3348 mCurrentState.layersSortedByZ.add(layer);
3349 // we need traversal (state changed)
3350 // AND transaction (list changed)
3351 flags |= eTransactionNeeded|eTraversalNeeded;
3352 }
chaviw8b3871a2017-11-01 17:41:01 -07003353 } else {
3354 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003355 flags |= eTransactionNeeded|eTraversalNeeded;
3356 }
3357 }
chaviw8b3871a2017-11-01 17:41:01 -07003358 }
3359 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003360 // NOTE: index needs to be calculated before we update the state
3361 const auto& p = layer->getParent();
3362 if (p == nullptr) {
3363 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3364 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3365 mCurrentState.layersSortedByZ.removeAt(idx);
3366 mCurrentState.layersSortedByZ.add(layer);
3367 // we need traversal (state changed)
3368 // AND transaction (list changed)
3369 flags |= eTransactionNeeded|eTraversalNeeded;
3370 }
3371 } else {
3372 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3373 flags |= eTransactionNeeded|eTraversalNeeded;
3374 }
chaviw8b3871a2017-11-01 17:41:01 -07003375 }
3376 }
3377 if (what & layer_state_t::eSizeChanged) {
3378 if (layer->setSize(s.w, s.h)) {
3379 flags |= eTraversalNeeded;
3380 }
3381 }
3382 if (what & layer_state_t::eAlphaChanged) {
3383 if (layer->setAlpha(s.alpha))
3384 flags |= eTraversalNeeded;
3385 }
3386 if (what & layer_state_t::eColorChanged) {
3387 if (layer->setColor(s.color))
3388 flags |= eTraversalNeeded;
3389 }
3390 if (what & layer_state_t::eMatrixChanged) {
3391 if (layer->setMatrix(s.matrix))
3392 flags |= eTraversalNeeded;
3393 }
3394 if (what & layer_state_t::eTransparentRegionChanged) {
3395 if (layer->setTransparentRegionHint(s.transparentRegion))
3396 flags |= eTraversalNeeded;
3397 }
3398 if (what & layer_state_t::eFlagsChanged) {
3399 if (layer->setFlags(s.flags, s.mask))
3400 flags |= eTraversalNeeded;
3401 }
3402 if (what & layer_state_t::eCropChanged) {
3403 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3404 flags |= eTraversalNeeded;
3405 }
3406 if (what & layer_state_t::eFinalCropChanged) {
3407 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3408 flags |= eTraversalNeeded;
3409 }
3410 if (what & layer_state_t::eLayerStackChanged) {
3411 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3412 // We only allow setting layer stacks for top level layers,
3413 // everything else inherits layer stack from its parent.
3414 if (layer->hasParent()) {
3415 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3416 layer->getName().string());
3417 } else if (idx < 0) {
3418 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3419 "that also does not appear in the top level layer list. Something"
3420 " has gone wrong.", layer->getName().string());
3421 } else if (layer->setLayerStack(s.layerStack)) {
3422 mCurrentState.layersSortedByZ.removeAt(idx);
3423 mCurrentState.layersSortedByZ.add(layer);
3424 // we need traversal (state changed)
3425 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003426 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003427 }
3428 }
3429 if (what & layer_state_t::eDeferTransaction) {
3430 if (s.barrierHandle != nullptr) {
3431 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3432 } else if (s.barrierGbp != nullptr) {
3433 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3434 if (authenticateSurfaceTextureLocked(gbp)) {
3435 const auto& otherLayer =
3436 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3437 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3438 } else {
3439 ALOGE("Attempt to defer transaction to to an"
3440 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003441 }
3442 }
chaviw8b3871a2017-11-01 17:41:01 -07003443 // We don't trigger a traversal here because if no other state is
3444 // changed, we don't want this to cause any more work
3445 }
3446 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003447 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003448 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003449 if (!hadParent) {
3450 mCurrentState.layersSortedByZ.remove(layer);
3451 }
chaviw8b3871a2017-11-01 17:41:01 -07003452 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003453 }
chaviw8b3871a2017-11-01 17:41:01 -07003454 }
3455 if (what & layer_state_t::eReparentChildren) {
3456 if (layer->reparentChildren(s.reparentHandle)) {
3457 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003458 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003459 }
chaviw8b3871a2017-11-01 17:41:01 -07003460 if (what & layer_state_t::eDetachChildren) {
3461 layer->detachChildren();
3462 }
3463 if (what & layer_state_t::eOverrideScalingModeChanged) {
3464 layer->setOverrideScalingMode(s.overrideScalingMode);
3465 // We don't trigger a traversal here because if no other state is
3466 // changed, we don't want this to cause any more work
3467 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003468 return flags;
3469}
3470
chaviwca27f252018-02-06 16:46:39 -08003471void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3472 const layer_state_t& state = composerState.state;
3473 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3474
3475 sp<Layer> layer(client->getLayerUser(state.surface));
3476 if (layer == nullptr) {
3477 return;
3478 }
3479
3480 if (layer->isPendingRemoval()) {
3481 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3482 return;
3483 }
3484
3485 if (state.what & layer_state_t::eDestroySurface) {
3486 removeLayerLocked(mStateLock, layer);
3487 }
3488}
3489
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003490status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003491 const String8& name,
3492 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003493 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliuccd34842018-03-14 12:26:23 -07003494 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003495 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003496{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003497 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003498 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003499 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003500 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003501 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003502
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003503 status_t result = NO_ERROR;
3504
3505 sp<Layer> layer;
3506
Cody Northropbc755282017-03-31 12:00:08 -06003507 String8 uniqueName = getUniqueLayerName(name);
3508
Mathias Agopian3165cc22012-08-08 19:42:09 -07003509 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3510 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003511 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003512 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003513 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003514
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003515 break;
chaviw13fdc492017-06-27 12:40:18 -07003516 case ISurfaceComposerClient::eFXSurfaceColor:
3517 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003518 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003519 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003520 break;
3521 default:
3522 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003523 break;
3524 }
3525
Dan Stoza7d89d062015-04-30 13:29:25 -07003526 if (result != NO_ERROR) {
3527 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003528 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003529
Chia-I Wuab0c3192017-08-01 11:29:00 -07003530 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3531 // TODO b/64227542
3532 if (windowType == 441731) {
3533 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3534 layer->setPrimaryDisplayOnly();
3535 }
3536
Albert Chaulk479c60c2017-01-27 14:21:34 -05003537 layer->setInfo(windowType, ownerUid);
3538
Robert Carr1f0a16a2016-10-24 16:27:39 -07003539 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003540 if (result != NO_ERROR) {
3541 return result;
3542 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003543 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003544
3545 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003546 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003547}
3548
Cody Northropbc755282017-03-31 12:00:08 -06003549String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3550{
3551 bool matchFound = true;
3552 uint32_t dupeCounter = 0;
3553
3554 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3555 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3556
3557 // Loop over layers until we're sure there is no matching name
3558 while (matchFound) {
3559 matchFound = false;
3560 mDrawingState.traverseInZOrder([&](Layer* layer) {
3561 if (layer->getName() == uniqueName) {
3562 matchFound = true;
3563 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3564 }
3565 });
3566 }
3567
3568 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3569
3570 return uniqueName;
3571}
3572
David Sodman0c69cad2017-08-21 12:12:51 -07003573status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003574 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3575 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003576{
3577 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003578 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003579 case PIXEL_FORMAT_TRANSPARENT:
3580 case PIXEL_FORMAT_TRANSLUCENT:
3581 format = PIXEL_FORMAT_RGBA_8888;
3582 break;
3583 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003584 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003585 break;
3586 }
3587
David Sodman0c69cad2017-08-21 12:12:51 -07003588 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3589 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003590 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003591 *handle = layer->getHandle();
3592 *gbp = layer->getProducer();
3593 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003594 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003595
David Sodman0c69cad2017-08-21 12:12:51 -07003596 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003597 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003598}
3599
chaviw13fdc492017-06-27 12:40:18 -07003600status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003601 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003602 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003603{
chaviw13fdc492017-06-27 12:40:18 -07003604 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003605 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003606 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003607}
3608
Mathias Agopianac9fa422013-02-11 16:40:36 -08003609status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003610{
Robert Carr9524cb32017-02-13 11:32:32 -08003611 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003612 status_t err = NO_ERROR;
3613 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003614 if (l != nullptr) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003615 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003616 err = removeLayer(l);
3617 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3618 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003619 }
3620 return err;
3621}
3622
Mathias Agopian13127d82013-03-05 17:47:11 -08003623status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003624{
Mathias Agopian67106042013-03-14 19:18:13 -07003625 // called by ~LayerCleaner() when all references to the IBinder (handle)
3626 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003627 sp<Layer> l = layer.promote();
3628 if (l == nullptr) {
3629 // The layer has already been removed, carry on
3630 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003631 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003632 // If we have a parent, then we can continue to live as long as it does.
3633 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003634}
3635
Mathias Agopianb60314a2012-04-10 22:09:54 -07003636// ---------------------------------------------------------------------------
3637
Andy McFadden13a082e2012-08-24 10:16:42 -07003638void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003639 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003640 Vector<ComposerState> state;
3641 Vector<DisplayState> displays;
3642 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003643 d.what = DisplayState::eDisplayProjectionChanged |
3644 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003645 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003646 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003647 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003648 d.frame.makeInvalid();
3649 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003650 d.width = 0;
3651 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003652 displays.add(d);
3653 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003654 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3655 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003656
David Sodman105b7dc2017-11-04 20:28:14 -07003657 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003658 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003659 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003660
Brian Andersond0010582017-03-07 13:20:31 -08003661 // Use phase of 0 since phase is not known.
3662 // Use latency of 0, which will snap to the ideal latency.
3663 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003664}
3665
3666void SurfaceFlinger::initializeDisplays() {
3667 class MessageScreenInitialized : public MessageBase {
3668 SurfaceFlinger* flinger;
3669 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003670 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003671 virtual bool handler() {
3672 flinger->onInitializeDisplays();
3673 return true;
3674 }
3675 };
3676 sp<MessageBase> msg = new MessageScreenInitialized(this);
3677 postMessageAsync(msg); // we may be called from main thread, use async message
3678}
3679
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003680void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003681 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003682 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3683 this);
3684 int32_t type = hw->getDisplayType();
3685 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003686
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003687 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003688 return;
3689 }
3690
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003691 hw->setPowerMode(mode);
3692 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3693 ALOGW("Trying to set power mode for virtual display");
3694 return;
3695 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003696
Lloyd Pique4d234852018-01-22 17:21:36 -08003697 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003698 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003699 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3700 if (idx < 0) {
3701 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3702 return;
3703 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003704 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003705 }
3706
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003707 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003708 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003709 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003710 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3711 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003712 // FIXME: eventthread only knows about the main display right now
3713 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003714 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003715 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003716
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003717 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003718 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003719 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003720
3721 struct sched_param param = {0};
3722 param.sched_priority = 1;
3723 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3724 ALOGW("Couldn't set SCHED_FIFO on display on");
3725 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003726 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003727 // Turn off the display
3728 struct sched_param param = {0};
3729 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3730 ALOGW("Couldn't set SCHED_OTHER on display off");
3731 }
3732
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003733 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3734 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003735 disableHardwareVsync(true); // also cancels any in-progress resync
3736
Mathias Agopiancde87a32012-09-13 14:09:01 -07003737 // FIXME: eventthread only knows about the main display right now
3738 mEventThread->onScreenReleased();
3739 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003740
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003741 getHwComposer().setPowerMode(type, mode);
3742 mVisibleRegionsDirty = true;
3743 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003744 } else if (mode == HWC_POWER_MODE_DOZE ||
3745 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003746 // Update display while dozing
3747 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003748 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3749 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003750 // FIXME: eventthread only knows about the main display right now
3751 mEventThread->onScreenAcquired();
3752 resyncToHardwareVsync(true);
3753 }
3754 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3755 // Leave display going to doze
3756 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3757 disableHardwareVsync(true); // also cancels any in-progress resync
3758 // FIXME: eventthread only knows about the main display right now
3759 mEventThread->onScreenReleased();
3760 }
3761 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003762 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003763 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003764 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003765 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003766 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003767}
3768
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003769void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3770 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003771 SurfaceFlinger& mFlinger;
3772 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003773 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003774 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003775 MessageSetPowerMode(SurfaceFlinger& flinger,
3776 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3777 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003778 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003779 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003780 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003781 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003782 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003783 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003784 ALOGW("Attempt to set power mode = %d for virtual display",
3785 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003786 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003787 mFlinger.setPowerModeInternal(
3788 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003789 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003790 return true;
3791 }
3792 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003793 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003794 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003795}
3796
3797// ---------------------------------------------------------------------------
3798
Lloyd Pique755e3192018-01-31 16:46:15 -08003799status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3800 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003801 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003802
Mathias Agopianbd115332013-04-18 16:41:04 -07003803 IPCThreadState* ipc = IPCThreadState::self();
3804 const int pid = ipc->getCallingPid();
3805 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003806
Mathias Agopianbd115332013-04-18 16:41:04 -07003807 if ((uid != AID_SHELL) &&
3808 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003809 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003810 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003811 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003812 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003813 // (this would indicate SF is stuck, but we want to be able to
3814 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003815 status_t err = mStateLock.timedLock(s2ns(1));
3816 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003817 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003818 result.appendFormat(
3819 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3820 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003821 }
3822
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003823 bool dumpAll = true;
3824 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003825 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003826
3827 if (asProto) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01003828 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviwa3d7bd32017-11-03 09:41:53 -07003829 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3830 dumpAll = false;
3831 }
3832
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003833 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003834 if ((index < numArgs) &&
3835 (args[index] == String16("--list"))) {
3836 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003837 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003838 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003839 }
3840
3841 if ((index < numArgs) &&
3842 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003843 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003844 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003845 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003846 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003847
3848 if ((index < numArgs) &&
3849 (args[index] == String16("--latency-clear"))) {
3850 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003851 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003852 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003853 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003854
3855 if ((index < numArgs) &&
3856 (args[index] == String16("--dispsync"))) {
3857 index++;
3858 mPrimaryDispSync.dump(result);
3859 dumpAll = false;
3860 }
Dan Stozab90cf072015-03-05 11:05:59 -08003861
3862 if ((index < numArgs) &&
3863 (args[index] == String16("--static-screen"))) {
3864 index++;
3865 dumpStaticScreenStats(result);
3866 dumpAll = false;
3867 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003868
3869 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003870 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003871 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003872 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003873 dumpAll = false;
3874 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003875
3876 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3877 index++;
3878 dumpWideColorInfo(result);
3879 dumpAll = false;
3880 }
Yiwei Zhang068e31b2018-02-21 13:02:45 -08003881
3882 if ((index < numArgs) &&
3883 (args[index] == String16("--enable-layer-stats"))) {
3884 index++;
3885 mLayerStats.enable();
3886 dumpAll = false;
3887 }
3888
3889 if ((index < numArgs) &&
3890 (args[index] == String16("--disable-layer-stats"))) {
3891 index++;
3892 mLayerStats.disable();
3893 dumpAll = false;
3894 }
3895
3896 if ((index < numArgs) &&
3897 (args[index] == String16("--clear-layer-stats"))) {
3898 index++;
3899 mLayerStats.clear();
3900 dumpAll = false;
3901 }
3902
3903 if ((index < numArgs) &&
3904 (args[index] == String16("--dump-layer-stats"))) {
3905 index++;
3906 mLayerStats.dump(result);
3907 dumpAll = false;
3908 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003909 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003910
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003911 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003912 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003913 }
3914
Mathias Agopian9795c422009-08-26 16:36:26 -07003915 if (locked) {
3916 mStateLock.unlock();
3917 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003918 }
3919 write(fd, result.string(), result.size());
3920 return NO_ERROR;
3921}
3922
Dan Stozac7014012014-02-14 15:03:43 -08003923void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3924 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003925{
Robert Carr2047fae2016-11-28 14:09:09 -08003926 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003927 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003928 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003929}
3930
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003931void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003932 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003933{
3934 String8 name;
3935 if (index < args.size()) {
3936 name = String8(args[index]);
3937 index++;
3938 }
3939
David Sodman105b7dc2017-11-04 20:28:14 -07003940 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003941 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003942 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003943
3944 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003945 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003946 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003947 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003948 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003949 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003950 }
Robert Carr2047fae2016-11-28 14:09:09 -08003951 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003952 }
3953}
3954
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003955void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003956 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003957{
3958 String8 name;
3959 if (index < args.size()) {
3960 name = String8(args[index]);
3961 index++;
3962 }
3963
Robert Carr2047fae2016-11-28 14:09:09 -08003964 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003965 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003966 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003967 }
Robert Carr2047fae2016-11-28 14:09:09 -08003968 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003969
Svetoslavd85084b2014-03-20 10:28:31 -07003970 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003971}
3972
Jamie Gennis6547ff42013-07-16 20:12:42 -07003973// This should only be called from the main thread. Otherwise it would need
3974// the lock and should use mCurrentState rather than mDrawingState.
3975void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003976 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003977 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003978 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003979
3980 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3981}
3982
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003983void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003984{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003985 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003986
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003987 if (isLayerTripleBufferingDisabled())
3988 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003989
3990 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003991 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003992 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003993 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003994 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3995 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003996 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003997}
3998
Dan Stozab90cf072015-03-05 11:05:59 -08003999void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4000{
4001 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004002 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4003 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004004 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004005 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004006 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4007 b + 1, bucketTimeSec, percent);
4008 }
David Sodman4a36e932017-11-07 14:29:47 -08004009 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004010 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004011 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004012 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004013 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004014}
4015
Dan Stozae77c7662016-05-13 11:37:28 -07004016void SurfaceFlinger::recordBufferingStats(const char* layerName,
4017 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004018 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4019 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004020 for (const auto& segment : history) {
4021 if (!segment.usedThirdBuffer) {
4022 stats.twoBufferTime += segment.totalTime;
4023 }
4024 if (segment.occupancyAverage < 1.0f) {
4025 stats.doubleBufferedTime += segment.totalTime;
4026 } else if (segment.occupancyAverage < 2.0f) {
4027 stats.tripleBufferedTime += segment.totalTime;
4028 }
4029 ++stats.numSegments;
4030 stats.totalTime += segment.totalTime;
4031 }
4032}
4033
Brian Andersond6927fb2016-07-23 23:37:30 -07004034void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4035 result.appendFormat("Layer frame timestamps:\n");
4036
4037 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4038 const size_t count = currentLayers.size();
4039 for (size_t i=0 ; i<count ; i++) {
4040 currentLayers[i]->dumpFrameEvents(result);
4041 }
4042}
4043
Dan Stozae77c7662016-05-13 11:37:28 -07004044void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4045 result.append("Buffering stats:\n");
4046 result.append(" [Layer name] <Active time> <Two buffer> "
4047 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004048 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004049 typedef std::tuple<std::string, float, float, float> BufferTuple;
4050 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004051 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004052 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004053 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004054 if (stats.numSegments == 0) {
4055 continue;
4056 }
4057 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4058 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4059 stats.totalTime;
4060 float doubleBufferRatio = static_cast<float>(
4061 stats.doubleBufferedTime) / stats.totalTime;
4062 float tripleBufferRatio = static_cast<float>(
4063 stats.tripleBufferedTime) / stats.totalTime;
4064 sorted.insert({activeTime, {name, twoBufferRatio,
4065 doubleBufferRatio, tripleBufferRatio}});
4066 }
4067 for (const auto& sortedPair : sorted) {
4068 float activeTime = sortedPair.first;
4069 const BufferTuple& values = sortedPair.second;
4070 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4071 std::get<0>(values).c_str(), activeTime,
4072 std::get<1>(values), std::get<2>(values),
4073 std::get<3>(values));
4074 }
4075 result.append("\n");
4076}
4077
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004078void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4079 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004080 result.appendFormat("DisplayColorSetting: %d\n", mDisplayColorSetting);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004081
4082 // TODO: print out if wide-color mode is active or not
4083
4084 for (size_t d = 0; d < mDisplays.size(); d++) {
4085 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4086 int32_t hwcId = displayDevice->getHwcDisplayId();
4087 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4088 continue;
4089 }
4090
4091 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004092 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004093 for (auto&& mode : modes) {
4094 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4095 }
4096
Peiyong Lina52f0292018-03-14 17:26:31 -07004097 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004098 result.appendFormat(" Current color mode: %s (%d)\n",
4099 decodeColorMode(currentMode).c_str(), currentMode);
4100 }
4101 result.append("\n");
4102}
4103
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004104LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004105 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004106 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4107 const State& state = useDrawing ? mDrawingState : mCurrentState;
4108 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004109 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004110 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004111 });
4112
4113 return layersProto;
4114}
4115
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004116LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4117 LayersProto layersProto;
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004118 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004119
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004120 SizeProto* resolution = layersProto.mutable_resolution();
4121 resolution->set_w(displayDevice->getWidth());
4122 resolution->set_h(displayDevice->getHeight());
4123
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004124 layersProto.set_color_mode(decodeColorMode(displayDevice->getActiveColorMode()));
4125 layersProto.set_color_transform(decodeColorTransform(displayDevice->getColorTransform()));
4126 layersProto.set_global_transform(
4127 static_cast<int32_t>(displayDevice->getOrientationTransform()));
4128
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004129 mDrawingState.traverseInZOrder([&](Layer* layer) {
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004130 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004131 LayerProto* layerProto = layersProto.add_layers();
4132 layer->writeToProto(layerProto, hwcId);
4133 }
4134 });
4135
4136 return layersProto;
4137}
4138
Mathias Agopian74d211a2013-04-22 16:55:35 +02004139void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4140 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004141{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004142 bool colorize = false;
4143 if (index < args.size()
4144 && (args[index] == String16("--color"))) {
4145 colorize = true;
4146 index++;
4147 }
4148
4149 Colorizer colorizer(colorize);
4150
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004151 // figure out if we're stuck somewhere
4152 const nsecs_t now = systemTime();
4153 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4154 const nsecs_t inTransaction(mDebugInTransaction);
4155 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4156 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4157
4158 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004159 * Dump library configuration.
4160 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004161
4162 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004163 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004164 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004165 appendSfConfigString(result);
4166 appendUiConfigString(result);
4167 appendGuiConfigString(result);
4168 result.append("\n");
4169
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004170 result.append("\nWide-Color information:\n");
4171 dumpWideColorInfo(result);
4172
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004173 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004174 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004175 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004176 result.append(SyncFeatures::getInstance().toString());
4177 result.append("\n");
4178
David Sodman105b7dc2017-11-04 20:28:14 -07004179 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004180
Andy McFadden41d67d72014-04-25 16:58:34 -07004181 colorizer.bold(result);
4182 result.append("DispSync configuration: ");
4183 colorizer.reset(result);
Dan Stoza2713c302018-03-28 17:07:36 -07004184 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, early sf phase %" PRId64
4185 " ns, present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4186 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, mVsyncModulator.getEarlyPhaseOffset(),
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004187 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004188 result.append("\n");
4189
Dan Stozab90cf072015-03-05 11:05:59 -08004190 // Dump static screen stats
4191 result.append("\n");
4192 dumpStaticScreenStats(result);
4193 result.append("\n");
4194
Dan Stozae77c7662016-05-13 11:37:28 -07004195 dumpBufferingStats(result);
4196
Andy McFadden4803b742012-09-24 19:07:20 -07004197 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004198 * Dump the visible layer list
4199 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004200 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004201 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004202 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4203 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004204 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004205
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004206 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004207 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7794ec12018-03-14 13:28:39 -07004208 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004209 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004210
4211 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004212 * Dump Display state
4213 */
4214
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004215 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004216 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004217 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004218 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4219 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004220 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004221 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004222 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004223
4224 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004225 * Dump SurfaceFlinger global state
4226 */
4227
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004228 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004229 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004230 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004231
Mathias Agopian888c8222012-08-04 21:10:38 -07004232 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004233 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004234
David Sodmanbc815282017-11-05 18:57:52 -08004235 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004236
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004237 if (hw) {
4238 hw->undefinedRegion.dump(result, "undefinedRegion");
4239 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4240 hw->getOrientation(), hw->isDisplayOn());
4241 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004242 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004243 " last eglSwapBuffers() time: %f us\n"
4244 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004245 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004246 " refresh-rate : %f fps\n"
4247 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004248 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004249 " gpu_to_cpu_unsupported : %d\n"
4250 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004251 mLastSwapBufferTime/1000.0,
4252 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004253 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004254 1e9 / activeConfig->getVsyncPeriod(),
4255 activeConfig->getDpiX(),
4256 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004257 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004258
Mathias Agopian74d211a2013-04-22 16:55:35 +02004259 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004260 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004261
Mathias Agopian74d211a2013-04-22 16:55:35 +02004262 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004263 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004264
4265 /*
4266 * VSYNC state
4267 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004268 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004269 result.append("\n");
4270
4271 /*
4272 * HWC layer minidump
4273 */
4274 for (size_t d = 0; d < mDisplays.size(); d++) {
4275 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4276 int32_t hwcId = displayDevice->getHwcDisplayId();
4277 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4278 continue;
4279 }
4280
4281 result.appendFormat("Display %d HWC layers:\n", hwcId);
4282 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004283 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004284 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004285 });
Dan Stozae22aec72016-08-01 13:20:59 -07004286 result.append("\n");
4287 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004288
4289 /*
4290 * Dump HWComposer state
4291 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004292 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004293 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004294 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004295 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004296 result.appendFormat(" h/w composer %s\n",
4297 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004298 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004299
4300 /*
4301 * Dump gralloc state
4302 */
4303 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4304 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004305
4306 /*
4307 * Dump VrFlinger state if in use.
4308 */
4309 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4310 result.append("VrFlinger state:\n");
4311 result.append(mVrFlinger->Dump().c_str());
4312 result.append("\n");
4313 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004314}
4315
Mathias Agopian13127d82013-03-05 17:47:11 -08004316const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004317SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004318 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004319 wp<IBinder> dpy;
4320 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4321 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4322 dpy = mDisplays.keyAt(i);
4323 break;
4324 }
4325 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004326 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004327 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4328 // Just use the primary display so we have something to return
4329 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4330 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004331 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004332}
4333
Keun young Park63f165f2012-08-31 10:53:36 -07004334bool SurfaceFlinger::startDdmConnection()
4335{
4336 void* libddmconnection_dso =
4337 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4338 if (!libddmconnection_dso) {
4339 return false;
4340 }
4341 void (*DdmConnection_start)(const char* name);
4342 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004343 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004344 if (!DdmConnection_start) {
4345 dlclose(libddmconnection_dso);
4346 return false;
4347 }
4348 (*DdmConnection_start)(getServiceName());
4349 return true;
4350}
4351
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004352status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004353 switch (code) {
4354 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004355 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004356 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004357 case CLEAR_ANIMATION_FRAME_STATS:
4358 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004359 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004360 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004361 case ENABLE_VSYNC_INJECTIONS:
4362 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004363 {
4364 // codes that require permission check
4365 IPCThreadState* ipc = IPCThreadState::self();
4366 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004367 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004368 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004369 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004370 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004371 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004372 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004373 break;
4374 }
Robert Carr1db73f62016-12-21 12:58:51 -08004375 /*
4376 * Calling setTransactionState is safe, because you need to have been
4377 * granted a reference to Client* and Handle* to do anything with it.
4378 *
4379 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4380 */
4381 case SET_TRANSACTION_STATE:
4382 case CREATE_SCOPED_CONNECTION:
4383 {
4384 return OK;
4385 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004386 case CAPTURE_SCREEN:
4387 {
4388 // codes that require permission check
4389 IPCThreadState* ipc = IPCThreadState::self();
4390 const int pid = ipc->getCallingPid();
4391 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004392 if ((uid != AID_GRAPHICS) &&
4393 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004394 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004395 return PERMISSION_DENIED;
4396 }
4397 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004398 }
chaviwa76b2712017-09-20 12:02:26 -07004399 case CAPTURE_LAYERS: {
4400 IPCThreadState* ipc = IPCThreadState::self();
4401 const int pid = ipc->getCallingPid();
4402 const int uid = ipc->getCallingUid();
4403 if ((uid != AID_GRAPHICS) &&
4404 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4405 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4406 return PERMISSION_DENIED;
4407 }
4408 break;
4409 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004410 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004411 return OK;
4412}
4413
4414status_t SurfaceFlinger::onTransact(
4415 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4416{
4417 status_t credentialCheck = CheckTransactCodeCredentials(code);
4418 if (credentialCheck != OK) {
4419 return credentialCheck;
4420 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004421
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004422 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4423 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004424 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004425 IPCThreadState* ipc = IPCThreadState::self();
4426 const int uid = ipc->getCallingUid();
4427 if (CC_UNLIKELY(uid != AID_SYSTEM
4428 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004429 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004430 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004431 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004432 return PERMISSION_DENIED;
4433 }
4434 int n;
4435 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004436 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004437 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004438 return NO_ERROR;
4439 case 1002: // SHOW_UPDATES
4440 n = data.readInt32();
4441 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004442 invalidateHwcGeometry();
4443 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004444 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004445 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004446 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004447 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004448 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004449 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004450 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004451 setTransactionFlags(
4452 eTransactionNeeded|
4453 eDisplayTransactionNeeded|
4454 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004455 return NO_ERROR;
4456 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004457 case 1006:{ // send empty update
4458 signalRefresh();
4459 return NO_ERROR;
4460 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004461 case 1008: // toggle use of hw composer
4462 n = data.readInt32();
4463 mDebugDisableHWC = n ? 1 : 0;
4464 invalidateHwcGeometry();
4465 repaintEverything();
4466 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004467 case 1009: // toggle use of transform hint
4468 n = data.readInt32();
4469 mDebugDisableTransformHint = n ? 1 : 0;
4470 invalidateHwcGeometry();
4471 repaintEverything();
4472 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004473 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004474 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004475 reply->writeInt32(0);
4476 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004477 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004478 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004479 return NO_ERROR;
4480 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004481 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004482 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004483 return NO_ERROR;
4484 }
4485 case 1014: {
4486 // daltonize
4487 n = data.readInt32();
4488 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004489 case 1:
4490 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4491 break;
4492 case 2:
4493 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4494 break;
4495 case 3:
4496 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4497 break;
4498 default:
4499 mDaltonizer.setType(ColorBlindnessType::None);
4500 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004501 }
4502 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004503 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004504 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004505 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004506 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004507 invalidateHwcGeometry();
4508 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004509 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004510 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004511 case 1015: {
4512 // apply a color matrix
4513 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004514 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004515 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004516 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004517 for (size_t j = 0; j < 4; j++) {
4518 mColorMatrix[i][j] = data.readFloat();
4519 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004520 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004521 } else {
4522 mColorMatrix = mat4();
4523 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004524
4525 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4526 // the division by w in the fragment shader
4527 float4 lastRow(transpose(mColorMatrix)[3]);
4528 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4529 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4530 }
4531
Alan Viverette9c5a3332013-09-12 20:04:35 -07004532 invalidateHwcGeometry();
4533 repaintEverything();
4534 return NO_ERROR;
4535 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004536 // This is an experimental interface
4537 // Needs to be shifted to proper binder interface when we productize
4538 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004539 n = data.readInt32();
4540 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004541 return NO_ERROR;
4542 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004543 case 1017: {
4544 n = data.readInt32();
4545 mForceFullDamage = static_cast<bool>(n);
4546 return NO_ERROR;
4547 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004548 case 1018: { // Modify Choreographer's phase offset
4549 n = data.readInt32();
4550 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4551 return NO_ERROR;
4552 }
4553 case 1019: { // Modify SurfaceFlinger's phase offset
4554 n = data.readInt32();
4555 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4556 return NO_ERROR;
4557 }
Irvel468051e2016-06-13 16:44:44 -07004558 case 1020: { // Layer updates interceptor
4559 n = data.readInt32();
4560 if (n) {
4561 ALOGV("Interceptor enabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004562 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004563 }
4564 else{
4565 ALOGV("Interceptor disabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004566 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004567 }
4568 return NO_ERROR;
4569 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004570 case 1021: { // Disable HWC virtual displays
4571 n = data.readInt32();
4572 mUseHwcVirtualDisplays = !n;
4573 return NO_ERROR;
4574 }
Romain Guy0147a172017-06-01 13:53:56 -07004575 case 1022: { // Set saturation boost
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004576 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004577
4578 invalidateHwcGeometry();
4579 repaintEverything();
4580 return NO_ERROR;
4581 }
Romain Guy54f154a2017-10-24 21:40:32 +01004582 case 1023: { // Set native mode
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004583 int32_t value = data.readInt32();
4584 if (value > 2) {
4585 return BAD_VALUE;
4586 }
4587 if (value == 2 && !mBuiltinDisplaySupportsEnhance) {
4588 return BAD_VALUE;
4589 }
Romain Guy54f154a2017-10-24 21:40:32 +01004590
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004591 mDisplayColorSetting = toDisplayColorSetting(value);
Romain Guy54f154a2017-10-24 21:40:32 +01004592 invalidateHwcGeometry();
4593 repaintEverything();
4594 return NO_ERROR;
4595 }
4596 case 1024: { // Is wide color gamut rendering/color management supported?
4597 reply->writeBool(hasWideColorDisplay);
4598 return NO_ERROR;
4599 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004600 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004601 n = data.readInt32();
4602 if (n) {
4603 ALOGV("LayerTracing enabled");
4604 mTracing.enable();
4605 doTracing("tracing.enable");
4606 reply->writeInt32(NO_ERROR);
4607 } else {
4608 ALOGV("LayerTracing disabled");
4609 status_t err = mTracing.disable();
4610 reply->writeInt32(err);
4611 }
4612 return NO_ERROR;
4613 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004614 case 1026: { // Get layer tracing status
4615 reply->writeBool(mTracing.isEnabled());
4616 return NO_ERROR;
4617 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004618 // Is a DisplayColorSetting supported?
4619 case 1027: {
4620 int32_t value = data.readInt32();
4621 switch (value) {
4622 case 0:
4623 reply->writeBool(hasWideColorDisplay);
4624 return NO_ERROR;
4625 case 1:
4626 reply->writeBool(true);
4627 return NO_ERROR;
4628 case 2:
4629 reply->writeBool(mBuiltinDisplaySupportsEnhance);
4630 return NO_ERROR;
4631 default:
4632 return BAD_VALUE;
4633 }
4634 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004635 }
4636 }
4637 return err;
4638}
4639
Steven Thomas6d8110b2017-08-31 18:24:21 -07004640void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004641 android_atomic_or(1, &mRepaintEverything);
4642 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004643}
4644
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004645// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4646class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004647public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004648 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4649 ~WindowDisconnector() {
4650 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004651 }
4652
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004653private:
4654 ANativeWindow* mWindow;
4655 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004656};
4657
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004658status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4659 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4660 int32_t minLayerZ, int32_t maxLayerZ,
4661 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004662 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004663 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004664
chaviwa76b2712017-09-20 12:02:26 -07004665 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4666
4667 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004668 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4669
chaviwa76b2712017-09-20 12:02:26 -07004670 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4671
4672 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4673 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004674 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004675}
4676
4677status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004678 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004679 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004680 ATRACE_CALL();
4681
4682 class LayerRenderArea : public RenderArea {
4683 public:
Robert Carr578038f2018-03-09 12:25:24 -08004684 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4685 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004686 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004687 mLayer(layer),
4688 mCrop(crop),
4689 mFlinger(flinger),
4690 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004691 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004692 Rect getBounds() const override {
4693 const Layer::State& layerState(mLayer->getDrawingState());
4694 return Rect(layerState.active.w, layerState.active.h);
4695 }
4696 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4697 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4698 bool isSecure() const override { return false; }
4699 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004700 Rect getSourceCrop() const override {
4701 if (mCrop.isEmpty()) {
4702 return getBounds();
4703 } else {
4704 return mCrop;
4705 }
4706 }
4707 bool getWideColorSupport() const override { return false; }
4708 Dataspace getDataSpace() const override { return Dataspace::UNKNOWN; }
Robert Carr578038f2018-03-09 12:25:24 -08004709
4710 class ReparentForDrawing {
4711 public:
4712 const sp<Layer>& oldParent;
4713 const sp<Layer>& newParent;
4714
4715 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4716 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004717 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004718 }
Robert Carr15eae092018-03-23 13:43:53 -07004719 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004720 };
4721
4722 void render(std::function<void()> drawLayers) override {
4723 if (!mChildrenOnly) {
4724 mTransform = mLayer->getTransform().inverse();
4725 drawLayers();
4726 } else {
4727 Rect bounds = getBounds();
4728 screenshotParentLayer =
4729 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4730 bounds.getWidth(), bounds.getHeight(), 0);
4731
4732 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4733 drawLayers();
4734 }
4735 }
chaviwa76b2712017-09-20 12:02:26 -07004736
chaviwa76b2712017-09-20 12:02:26 -07004737 private:
chaviw7206d492017-11-10 16:16:12 -08004738 const sp<Layer> mLayer;
4739 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004740
4741 // In the "childrenOnly" case we reparent the children to a screenshot
4742 // layer which has no properties set and which does not draw.
4743 sp<ContainerLayer> screenshotParentLayer;
4744 Transform mTransform;
4745
4746 SurfaceFlinger* mFlinger;
4747 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004748 };
4749
4750 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4751 auto parent = layerHandle->owner.promote();
4752
chaviw7206d492017-11-10 16:16:12 -08004753 if (parent == nullptr || parent->isPendingRemoval()) {
4754 ALOGE("captureLayers called with a removed parent");
4755 return NAME_NOT_FOUND;
4756 }
4757
Robert Carr578038f2018-03-09 12:25:24 -08004758 const int uid = IPCThreadState::self()->getCallingUid();
4759 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4760 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4761 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4762 return PERMISSION_DENIED;
4763 }
4764
chaviw7206d492017-11-10 16:16:12 -08004765 Rect crop(sourceCrop);
4766 if (sourceCrop.width() <= 0) {
4767 crop.left = 0;
4768 crop.right = parent->getCurrentState().active.w;
4769 }
4770
4771 if (sourceCrop.height() <= 0) {
4772 crop.top = 0;
4773 crop.bottom = parent->getCurrentState().active.h;
4774 }
4775
4776 int32_t reqWidth = crop.width() * frameScale;
4777 int32_t reqHeight = crop.height() * frameScale;
4778
Robert Carr578038f2018-03-09 12:25:24 -08004779 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004780
Robert Carr578038f2018-03-09 12:25:24 -08004781 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004782 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4783 if (!layer->isVisible()) {
4784 return;
Robert Carr578038f2018-03-09 12:25:24 -08004785 } else if (childrenOnly && layer == parent.get()) {
4786 return;
chaviwa76b2712017-09-20 12:02:26 -07004787 }
4788 visitor(layer);
4789 });
4790 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004791 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004792}
4793
4794status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4795 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004796 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004797 bool useIdentityTransform) {
4798 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004799
chaviwa76b2712017-09-20 12:02:26 -07004800 renderArea.updateDimensions();
4801
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004802 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4803 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4804 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4805 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004806
4807 // This mutex protects syncFd and captureResult for communication of the return values from the
4808 // main thread back to this Binder thread
4809 std::mutex captureMutex;
4810 std::condition_variable captureCondition;
4811 std::unique_lock<std::mutex> captureLock(captureMutex);
4812 int syncFd = -1;
4813 std::optional<status_t> captureResult;
4814
Robert Carr03480e22018-01-04 16:02:06 -08004815 const int uid = IPCThreadState::self()->getCallingUid();
4816 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4817
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004818 sp<LambdaMessage> message = new LambdaMessage([&]() {
4819 // If there is a refresh pending, bug out early and tell the binder thread to try again
4820 // after the refresh.
4821 if (mRefreshPending) {
4822 ATRACE_NAME("Skipping screenshot for now");
4823 std::unique_lock<std::mutex> captureLock(captureMutex);
4824 captureResult = std::make_optional<status_t>(EAGAIN);
4825 captureCondition.notify_one();
4826 return;
4827 }
4828
4829 status_t result = NO_ERROR;
4830 int fd = -1;
4831 {
4832 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004833 renderArea.render([&]() {
4834 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4835 useIdentityTransform, forSystem, &fd);
4836 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004837 }
4838
4839 {
4840 std::unique_lock<std::mutex> captureLock(captureMutex);
4841 syncFd = fd;
4842 captureResult = std::make_optional<status_t>(result);
4843 captureCondition.notify_one();
4844 }
4845 });
4846
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004847 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004848 if (result == NO_ERROR) {
4849 captureCondition.wait(captureLock, [&]() { return captureResult; });
4850 while (*captureResult == EAGAIN) {
4851 captureResult.reset();
4852 result = postMessageAsync(message);
4853 if (result != NO_ERROR) {
4854 return result;
4855 }
4856 captureCondition.wait(captureLock, [&]() { return captureResult; });
4857 }
4858 result = *captureResult;
4859 }
4860
4861 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004862 sync_wait(syncFd, -1);
4863 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004864 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004865
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004866 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004867}
4868
chaviwa76b2712017-09-20 12:02:26 -07004869void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4870 TraverseLayersFunction traverseLayers, bool yswap,
4871 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004872 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004873
Lloyd Pique144e1162017-12-20 16:44:52 -08004874 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004875
4876 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004877 const auto raWidth = renderArea.getWidth();
4878 const auto raHeight = renderArea.getHeight();
4879
4880 const auto reqWidth = renderArea.getReqWidth();
4881 const auto reqHeight = renderArea.getReqHeight();
4882 Rect sourceCrop = renderArea.getSourceCrop();
4883
4884 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4885 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004886
Dan Stozac1879002014-05-22 15:59:05 -07004887 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004888 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004889 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004890 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07004891 }
4892
4893 // ensure that sourceCrop is inside screen
4894 if (sourceCrop.left < 0) {
4895 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4896 }
chaviwa76b2712017-09-20 12:02:26 -07004897 if (sourceCrop.right > raWidth) {
4898 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07004899 }
4900 if (sourceCrop.top < 0) {
4901 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4902 }
chaviwa76b2712017-09-20 12:02:26 -07004903 if (sourceCrop.bottom > raHeight) {
4904 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07004905 }
4906
Peiyong Lin34beb7a2018-03-28 11:57:12 -07004907 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004908 if (renderArea.getWideColorSupport()) {
4909 outputDataspace = renderArea.getDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08004910 }
4911 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Romain Guy88d37dd2017-05-26 17:57:05 -07004912
Mathias Agopian180f10d2013-04-10 22:55:41 -07004913 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004914 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004915
4916 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07004917 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
4918 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07004919 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004920
chaviw50da5042018-04-09 13:49:37 -07004921 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004922 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07004923 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004924
chaviwa76b2712017-09-20 12:02:26 -07004925 traverseLayers([&](Layer* layer) {
4926 if (filtering) layer->setFiltering(true);
4927 layer->draw(renderArea, useIdentityTransform);
4928 if (filtering) layer->setFiltering(false);
4929 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07004930}
4931
chaviwa76b2712017-09-20 12:02:26 -07004932status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
4933 TraverseLayersFunction traverseLayers,
4934 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004935 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08004936 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07004937 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004938 ATRACE_CALL();
4939
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004940 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07004941
4942 traverseLayers([&](Layer* layer) {
4943 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
4944 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004945
Robert Carr03480e22018-01-04 16:02:06 -08004946 // We allow the system server to take screenshots of secure layers for
4947 // use in situations like the Screen-rotation animation and place
4948 // the impetus on WindowManager to not persist them.
4949 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004950 ALOGW("FB is protected: PERMISSION_DENIED");
4951 return PERMISSION_DENIED;
4952 }
4953
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004954 // this binds the given EGLImage as a framebuffer for the
4955 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08004956 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08004957 if (bufferBond.getStatus() != NO_ERROR) {
4958 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004959 return INVALID_OPERATION;
4960 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004961
Dan Stozaabcda352017-06-01 14:37:39 -07004962 // this will in fact render into our dequeued buffer
4963 // via an FBO, which means we didn't have to create
4964 // an EGLSurface and therefore we're not
4965 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07004966 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004967
Dan Stozaabcda352017-06-01 14:37:39 -07004968 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08004969 getRenderEngine().finish();
4970 *outSyncFd = -1;
4971
chaviwa76b2712017-09-20 12:02:26 -07004972 const auto reqWidth = renderArea.getReqWidth();
4973 const auto reqHeight = renderArea.getReqHeight();
4974
Dan Stozaabcda352017-06-01 14:37:39 -07004975 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4976 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07004977 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07004978 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08004979 } else {
4980 base::unique_fd syncFd = getRenderEngine().flush();
4981 if (syncFd < 0) {
4982 getRenderEngine().finish();
4983 }
4984 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07004985 }
4986
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004987 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004988}
4989
Mathias Agopiand5556842013-09-19 17:08:37 -07004990void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07004991 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004992 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07004993 for (size_t y = 0; y < h; y++) {
4994 uint32_t const* p = (uint32_t const*)vaddr + y * s;
4995 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004996 if (p[x] != 0xFF000000) return;
4997 }
4998 }
chaviwa76b2712017-09-20 12:02:26 -07004999 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005000
Robert Carr2047fae2016-11-28 14:09:09 -08005001 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005002 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005003 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005004 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5005 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5006 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5007 static_cast<float>(state.color.a));
5008 i++;
5009 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005010 }
5011}
5012
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005013// ---------------------------------------------------------------------------
5014
Dan Stoza412903f2017-04-27 13:42:17 -07005015void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5016 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005017}
5018
Dan Stoza412903f2017-04-27 13:42:17 -07005019void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5020 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005021}
5022
chaviwa76b2712017-09-20 12:02:26 -07005023void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
5024 int32_t maxLayerZ,
5025 const LayerVector::Visitor& visitor) {
5026 // We loop through the first level of layers without traversing,
5027 // as we need to interpret min/max layer Z in the top level Z space.
5028 for (const auto& layer : mDrawingState.layersSortedByZ) {
5029 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5030 continue;
5031 }
5032 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005033 // relative layers are traversed in Layer::traverseInZOrder
5034 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005035 continue;
5036 }
5037 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005038 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5039 return;
5040 }
chaviwa76b2712017-09-20 12:02:26 -07005041 if (!layer->isVisible()) {
5042 return;
5043 }
5044 visitor(layer);
5045 });
5046 }
5047}
5048
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005049}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005050
5051
5052#if defined(__gl_h_)
5053#error "don't include gl/gl.h in this file"
5054#endif
5055
5056#if defined(__gl2_h_)
5057#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005058#endif