blob: a837d01d80ca8eace5b1ee9a9de2b5553838a452 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060040#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070041#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070042#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043
Jamie Gennis1a4d8832012-08-02 20:11:05 -070044#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070045#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080047#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080048#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070049
50#include <ui/GraphicBufferAllocator.h>
51#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080053
Mathias Agopiancde87a32012-09-13 14:09:01 -070054#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080055#include <utils/String8.h>
56#include <utils/String16.h>
57#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070058#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080059#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060
Mathias Agopian921e6ac2012-07-23 23:11:29 -070061#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070062#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063
Robert Carr578038f2018-03-09 12:25:24 -080064#include "BufferLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020065#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080066#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020067#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080068#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080069#include "DdmConnection.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070070#include "DispSync.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "DisplayDevice.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070072#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080073#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
Robert Carr578038f2018-03-09 12:25:24 -080078#include "clz.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Steven Thomasb02664d2017-07-26 18:48:28 -070080#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070081#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070082#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070083#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084
Mathias Agopianff2ed702013-09-01 21:36:12 -070085#include "Effects/Daltonizer.h"
86
Mathias Agopian875d8e12013-06-07 15:35:48 -070087#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070088#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070089
Jiyong Park4b20c2e2017-01-14 19:45:11 +090090#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090091#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090092
chaviw1d044282017-09-27 12:19:28 -070093#include <layerproto/LayerProtoParser.h>
94
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080095#define DISPLAY_COUNT 1
96
Mathias Agopianfee2b462013-07-03 12:34:01 -070097/*
98 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
99 * black pixels.
100 */
101#define DEBUG_SCREENSHOTS false
102
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800103namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700104
Jaesoo Lee43518572017-01-23 19:03:16 +0900105using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900106using namespace android::hardware::configstore::V1_0;
Peiyong Linfd997e02018-03-28 15:29:00 -0700107using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700108using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700109using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700110using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900111
Steven Thomasb02664d2017-07-26 18:48:28 -0700112namespace {
113class ConditionalLock {
114public:
115 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
116 if (lock) {
117 mMutex.lock();
118 }
119 }
120 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
121private:
122 Mutex& mMutex;
123 bool mLocked;
124};
125} // namespace anonymous
126
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800127// ---------------------------------------------------------------------------
128
Mathias Agopian99b49842011-06-27 16:05:52 -0700129const String16 sHardwareTest("android.permission.HARDWARE_TEST");
130const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
131const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
132const String16 sDump("android.permission.DUMP");
133
134// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800135int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
136int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700137int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700138bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800139uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800140bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800141bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800142int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800143// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600144bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700145
Kalle Raitaa099a242017-01-11 11:17:29 -0800146
147std::string getHwcServiceName() {
148 char value[PROPERTY_VALUE_MAX] = {};
149 property_get("debug.sf.hwc_service_name", value, "default");
150 ALOGI("Using HWComposer service: '%s'", value);
151 return std::string(value);
152}
153
154bool useTrebleTestingOverride() {
155 char value[PROPERTY_VALUE_MAX] = {};
156 property_get("debug.sf.treble_testing_override", value, "false");
157 ALOGI("Treble testing override: '%s'", value);
158 return std::string(value) == "true";
159}
160
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800161DisplayColorSetting toDisplayColorSetting(int value) {
162 switch(value) {
163 case 0:
164 return DisplayColorSetting::MANAGED;
165 case 1:
166 return DisplayColorSetting::UNMANAGED;
167 case 2:
168 return DisplayColorSetting::ENHANCED;
169 default:
170 return DisplayColorSetting::MANAGED;
171 }
172}
173
174std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
175 switch(displayColorSetting) {
176 case DisplayColorSetting::MANAGED:
177 return std::string("Natural Mode");
178 case DisplayColorSetting::UNMANAGED:
179 return std::string("Saturated Mode");
180 case DisplayColorSetting::ENHANCED:
181 return std::string("Auto Color Mode");
182 }
183 return std::string("Unknown Display Color Setting");
184}
185
Lloyd Pique09594832018-01-22 17:48:03 -0800186NativeWindowSurface::~NativeWindowSurface() = default;
187
188namespace impl {
189
190class NativeWindowSurface final : public android::NativeWindowSurface {
191public:
192 static std::unique_ptr<android::NativeWindowSurface> create(
193 const sp<IGraphicBufferProducer>& producer) {
194 return std::make_unique<NativeWindowSurface>(producer);
195 }
196
197 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
198 : surface(new Surface(producer, false)) {}
199
200 ~NativeWindowSurface() override = default;
201
202private:
203 sp<ANativeWindow> getNativeWindow() const override { return surface; }
204
205 void preallocateBuffers() override { surface->allocateBuffers(); }
206
207 sp<Surface> surface;
208};
209
210} // namespace impl
211
David Sodmanbc815282017-11-05 18:57:52 -0800212SurfaceFlingerBE::SurfaceFlingerBE()
213 : mHwcServiceName(getHwcServiceName()),
214 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800215 mFrameBuckets(),
216 mTotalTime(0),
217 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800218 mComposerSequenceId(0) {
219}
220
Lloyd Pique2d3ee6d2018-01-17 13:42:24 -0800221SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800222 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800223 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700224 mTransactionPending(false),
225 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700226 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700227 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700228 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800229 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800230 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800231 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800232 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800233 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800234 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700235 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700236 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700237 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700238 mDebugInSwapBuffers(0),
239 mLastSwapBufferTime(0),
240 mDebugInTransaction(0),
241 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700242 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700243 mForceFullDamage(false),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000244 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700245 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700246 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800247 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800248 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700249 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800250 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique09594832018-01-22 17:48:03 -0800251 mCreateBufferQueue(&BufferQueue::createBufferQueue),
252 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Pique2d3ee6d2018-01-17 13:42:24 -0800253
254SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800255 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800256
257 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
258 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
259
260 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
261 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
262
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800263 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
264 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800265
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700266 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
267 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
268
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700269 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
270 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
271
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800272 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
273 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
274
Steven Thomas050b2c82017-03-06 11:45:16 -0800275 // Vr flinger is only enabled on Daydream ready devices.
276 useVrFlinger = getBool< ISurfaceFlingerConfigs,
277 &ISurfaceFlingerConfigs::useVrFlinger>(false);
278
Fabien Sanglard1971b632017-03-10 14:50:03 -0800279 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
280 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
281
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600282 hasWideColorDisplay =
283 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
284
David Sodman99974d22017-11-28 12:04:33 -0800285 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700286
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800287 // debugging stuff...
288 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700289
Mathias Agopianb4b17302013-03-20 18:36:41 -0700290 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700291 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700292
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800293 property_get("debug.sf.showupdates", value, "0");
294 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700295
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700296 property_get("debug.sf.ddms", value, "0");
297 mDebugDDMS = atoi(value);
298 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700299 if (!startDdmConnection()) {
300 // start failed, and DDMS debugging not enabled
301 mDebugDDMS = 0;
302 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700303 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700304 ALOGI_IF(mDebugRegion, "showupdates enabled");
305 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700306
307 property_get("debug.sf.disable_backpressure", value, "0");
308 mPropagateBackpressure = !atoi(value);
309 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700310
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800311 property_get("debug.sf.enable_hwc_vds", value, "0");
312 mUseHwcVirtualDisplays = atoi(value);
313 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800314
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800315 property_get("ro.sf.disable_triple_buffer", value, "1");
316 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800317 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700318
Dan Stoza0a0158c2018-03-16 13:38:54 -0700319 // TODO (b/74616334): Reduce the default value once we isolate the leak
320 const size_t defaultListSize = 4 * MAX_LAYERS;
321 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
322 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
323
Dan Stoza2713c302018-03-28 17:07:36 -0700324 property_get("debug.sf.early_phase_offset_ns", value, "0");
325 const int earlyWakeupOffsetOffsetNs = atoi(value);
326 ALOGI_IF(earlyWakeupOffsetOffsetNs != 0, "Enabling separate early offset");
327 mVsyncModulator.setPhaseOffsets(sfVsyncPhaseOffsetNs - earlyWakeupOffsetOffsetNs,
328 sfVsyncPhaseOffsetNs);
329
Romain Guy11d63f42017-07-20 12:47:14 -0700330 // We should be reading 'persist.sys.sf.color_saturation' here
331 // but since /data may be encrypted, we need to wait until after vold
332 // comes online to attempt to read the property. The property is
333 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800334
335 if (useTrebleTestingOverride()) {
336 // Without the override SurfaceFlinger cannot connect to HIDL
337 // services that are not listed in the manifests. Considered
338 // deriving the setting from the set service name, but it
339 // would be brittle if the name that's not 'default' is used
340 // for production purposes later on.
341 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
342 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800343}
344
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800345void SurfaceFlinger::onFirstRef()
346{
Lloyd Pique9123ae52018-01-22 17:14:00 -0800347 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800348}
349
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800350SurfaceFlinger::~SurfaceFlinger()
351{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800352}
353
Dan Stozac7014012014-02-14 15:03:43 -0800354void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800355{
356 // the window manager died on us. prepare its eulogy.
357
Andy McFadden13a082e2012-08-24 10:16:42 -0700358 // restore initial conditions (default device unblank, etc)
359 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800360
361 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700362 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800363}
364
Robert Carr1db73f62016-12-21 12:58:51 -0800365static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700366 status_t err = client->initCheck();
367 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800368 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800369 }
Robert Carr1db73f62016-12-21 12:58:51 -0800370 return nullptr;
371}
372
373sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
374 return initClient(new Client(this));
375}
376
377sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
378 const sp<IGraphicBufferProducer>& gbp) {
379 if (authenticateSurfaceTexture(gbp) == false) {
380 return nullptr;
381 }
382 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
383 if (layer == nullptr) {
384 return nullptr;
385 }
386
387 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800388}
389
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700390sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
391 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700392{
393 class DisplayToken : public BBinder {
394 sp<SurfaceFlinger> flinger;
395 virtual ~DisplayToken() {
396 // no more references, this display must be terminated
397 Mutex::Autolock _l(flinger->mStateLock);
398 flinger->mCurrentState.displays.removeItem(this);
399 flinger->setTransactionFlags(eDisplayTransactionNeeded);
400 }
401 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700402 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700403 : flinger(flinger) {
404 }
405 };
406
407 sp<BBinder> token = new DisplayToken(this);
408
409 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700410 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700411 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700412 mCurrentState.displays.add(token, info);
Lloyd Pique4d234852018-01-22 17:21:36 -0800413 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700414 return token;
415}
416
Jesse Hall6c913be2013-08-08 12:15:49 -0700417void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
418 Mutex::Autolock _l(mStateLock);
419
420 ssize_t idx = mCurrentState.displays.indexOfKey(display);
421 if (idx < 0) {
422 ALOGW("destroyDisplay: invalid display token");
423 return;
424 }
425
426 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
427 if (!info.isVirtualDisplay()) {
428 ALOGE("destroyDisplay called for non-virtual display");
429 return;
430 }
Lloyd Pique4d234852018-01-22 17:21:36 -0800431 mInterceptor->saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700432 mCurrentState.displays.removeItemsAt(idx);
433 setTransactionFlags(eDisplayTransactionNeeded);
434}
435
Mathias Agopiane57f2922012-08-09 16:29:12 -0700436sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700437 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700438 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800439 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700440 }
Jesse Hall692c7232012-11-08 15:41:56 -0800441 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700442}
443
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800444void SurfaceFlinger::bootFinished()
445{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700446 if (mStartPropertySetThread->join() != NO_ERROR) {
447 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800448 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800449 const nsecs_t now = systemTime();
450 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000451 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700452
453 // wait patiently for the window manager death
454 const String16 name("window");
455 sp<IBinder> window(defaultServiceManager()->getService(name));
456 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700457 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700458 }
459
Steven Thomas050b2c82017-03-06 11:45:16 -0800460 if (mVrFlinger) {
461 mVrFlinger->OnBootFinished();
462 }
463
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700464 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700465 // formerly we would just kill the process, but we now ask it to exit so it
466 // can choose where to stop the animation.
467 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700468
469 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
470 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
471 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700472
Thierry Strudel2924d012017-08-14 15:19:37 -0700473 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700474 readPersistentProperties();
475 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700476 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800477}
478
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");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800639 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
640 [this]() { resyncWithRateLimit(); },
641 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800642 "appEventThread");
643 mSfEventThreadSource =
644 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
645 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800646
Lloyd Pique24b0a482018-03-09 18:52:26 -0800647 mSFEventThread =
648 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
649 [this]() { resyncWithRateLimit(); },
650 [this](nsecs_t timestamp) {
651 mInterceptor->saveVSyncEvent(timestamp);
652 },
653 "sfEventThread");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800654 mEventQueue->setEventThread(mSFEventThread.get());
Dan Stoza2713c302018-03-28 17:07:36 -0700655 mVsyncModulator.setEventThread(mSFEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800656
Steven Thomasb02664d2017-07-26 18:48:28 -0700657 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800658 getBE().mRenderEngine =
659 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
660 hasWideColorDisplay
661 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
662 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800663 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700664
665 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
666 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800667 getBE().mHwc.reset(
668 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700669 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800670 // Process any initial hotplug and resulting display changes.
671 processDisplayHotplugEventsLocked();
672 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
673 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800674
Lloyd Piquefcd86612017-12-14 17:15:36 -0800675 // make the default display GLContext current so that we can create textures
676 // when creating Layers (which may happens before we render something)
677 getDefaultDisplayDeviceLocked()->makeCurrent();
678
Steven Thomas050b2c82017-03-06 11:45:16 -0800679 if (useVrFlinger) {
680 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700681 // This callback is called from the vr flinger dispatch thread. We
682 // need to call signalTransaction(), which requires holding
683 // mStateLock when we're not on the main thread. Acquiring
684 // mStateLock from the vr flinger dispatch thread might trigger a
685 // deadlock in surface flinger (see b/66916578), so post a message
686 // to be handled on the main thread instead.
687 sp<LambdaMessage> message = new LambdaMessage([=]() {
688 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
689 mVrFlingerRequestsDisplay = requestDisplay;
690 signalTransaction();
691 });
692 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800693 };
David Sodman105b7dc2017-11-04 20:28:14 -0700694 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
695 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800696 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800697 if (!mVrFlinger) {
698 ALOGE("Failed to start vrflinger");
699 }
700 }
701
Lloyd Pique0c3a8832018-01-22 17:31:47 -0800702 mEventControlThread = std::make_unique<impl::EventControlThread>(
703 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700704
Mathias Agopian92a979a2012-08-02 18:32:23 -0700705 // initialize our drawing state
706 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700707
Andy McFadden13a082e2012-08-24 10:16:42 -0700708 // set initial conditions (e.g. unblank default device)
709 initializeDisplays();
710
David Sodmanbc815282017-11-05 18:57:52 -0800711 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700712
Wei Wangf9b05ee2017-07-19 20:59:39 -0700713 // Inform native graphics APIs whether the present timestamp is supported:
714 if (getHwComposer().hasCapability(
715 HWC2::Capability::PresentFenceIsNotReliable)) {
716 mStartPropertySetThread = new StartPropertySetThread(false);
717 } else {
718 mStartPropertySetThread = new StartPropertySetThread(true);
719 }
720
721 if (mStartPropertySetThread->Start() != NO_ERROR) {
722 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800723 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800724
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800725 mLegacySrgbSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(HWC_DISPLAY_PRIMARY,
726 Dataspace::SRGB_LINEAR);
727
Dan Stoza9e56aa02015-11-02 13:00:03 -0800728 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700729}
730
Romain Guy11d63f42017-07-20 12:47:14 -0700731void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700732 Mutex::Autolock _l(mStateLock);
733
Romain Guy11d63f42017-07-20 12:47:14 -0700734 char value[PROPERTY_VALUE_MAX];
735
736 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800737 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700738 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800739 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100740
741 property_get("persist.sys.sf.native_mode", value, "0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800742 mDisplayColorSetting = toDisplayColorSetting(atoi(value));
743 ALOGV("Display Color Setting is set to %s.",
744 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Romain Guy11d63f42017-07-20 12:47:14 -0700745}
746
Mathias Agopiana67e4182012-06-19 17:26:12 -0700747void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800748 // Start boot animation service by setting a property mailbox
749 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700750 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800751 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700752 if (mStartPropertySetThread->join() != NO_ERROR) {
753 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800754 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700755}
756
Mathias Agopian875d8e12013-06-07 15:35:48 -0700757size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800758 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700759}
760
Mathias Agopian875d8e12013-06-07 15:35:48 -0700761size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800762 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700763}
764
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800765// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800766
Jamie Gennis582270d2011-08-17 18:19:00 -0700767bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800768 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800769 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800770 return authenticateSurfaceTextureLocked(bufferProducer);
771}
772
773bool SurfaceFlinger::authenticateSurfaceTextureLocked(
774 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800775 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800776 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800777}
778
Brian Anderson6b376712017-04-04 10:51:39 -0700779status_t SurfaceFlinger::getSupportedFrameTimestamps(
780 std::vector<FrameEvent>* outSupported) const {
781 *outSupported = {
782 FrameEvent::REQUESTED_PRESENT,
783 FrameEvent::ACQUIRE,
784 FrameEvent::LATCH,
785 FrameEvent::FIRST_REFRESH_START,
786 FrameEvent::LAST_REFRESH_START,
787 FrameEvent::GPU_COMPOSITION_DONE,
788 FrameEvent::DEQUEUE_READY,
789 FrameEvent::RELEASE,
790 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700791 ConditionalLock _l(mStateLock,
792 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700793 if (!getHwComposer().hasCapability(
794 HWC2::Capability::PresentFenceIsNotReliable)) {
795 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
796 }
797 return NO_ERROR;
798}
799
Dan Stoza7f7da322014-05-02 15:26:25 -0700800status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
801 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800802 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700803 return BAD_VALUE;
804 }
805
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500806 if (!display.get())
807 return NAME_NOT_FOUND;
808
Jesse Hall692c7232012-11-08 15:41:56 -0800809 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700810 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800811 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700812 type = i;
813 break;
814 }
815 }
816
817 if (type < 0) {
818 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700819 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700820
Mathias Agopian8b736f12012-08-13 17:54:26 -0700821 // TODO: Not sure if display density should handled by SF any longer
822 class Density {
823 static int getDensityFromProperty(char const* propName) {
824 char property[PROPERTY_VALUE_MAX];
825 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800826 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700827 density = atoi(property);
828 }
829 return density;
830 }
831 public:
832 static int getEmuDensity() {
833 return getDensityFromProperty("qemu.sf.lcd_density"); }
834 static int getBuildDensity() {
835 return getDensityFromProperty("ro.sf.lcd_density"); }
836 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700837
Dan Stoza7f7da322014-05-02 15:26:25 -0700838 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700839
Steven Thomas6d8110b2017-08-31 18:24:21 -0700840 ConditionalLock _l(mStateLock,
841 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800842 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700843 DisplayInfo info = DisplayInfo();
844
Dan Stoza9e56aa02015-11-02 13:00:03 -0800845 float xdpi = hwConfig->getDpiX();
846 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700847
848 if (type == DisplayDevice::DISPLAY_PRIMARY) {
849 // The density of the device is provided by a build property
850 float density = Density::getBuildDensity() / 160.0f;
851 if (density == 0) {
852 // the build doesn't provide a density -- this is wrong!
853 // use xdpi instead
854 ALOGE("ro.sf.lcd_density must be defined as a build property");
855 density = xdpi / 160.0f;
856 }
857 if (Density::getEmuDensity()) {
858 // if "qemu.sf.lcd_density" is specified, it overrides everything
859 xdpi = ydpi = density = Density::getEmuDensity();
860 density /= 160.0f;
861 }
862 info.density = density;
863
864 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700865 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800866 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700867 } else {
868 // TODO: where should this value come from?
869 static const int TV_DENSITY = 213;
870 info.density = TV_DENSITY / 160.0f;
871 info.orientation = 0;
872 }
873
Dan Stoza9e56aa02015-11-02 13:00:03 -0800874 info.w = hwConfig->getWidth();
875 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700876 info.xdpi = xdpi;
877 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800878 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900879 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800880
Andy McFadden91b2ca82014-06-13 14:04:23 -0700881 // This is how far in advance a buffer must be queued for
882 // presentation at a given time. If you want a buffer to appear
883 // on the screen at time N, you must submit the buffer before
884 // (N - presentationDeadline).
885 //
886 // Normally it's one full refresh period (to give SF a chance to
887 // latch the buffer), but this can be reduced by configuring a
888 // DispSync offset. Any additional delays introduced by the hardware
889 // composer or panel must be accounted for here.
890 //
891 // We add an additional 1ms to allow for processing time and
892 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800893 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800894 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700895
896 // All non-virtual displays are currently considered secure.
897 info.secure = true;
898
Michael Wright28f24d02016-07-12 13:30:53 -0700899 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700900 }
901
Dan Stoza7f7da322014-05-02 15:26:25 -0700902 return NO_ERROR;
903}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700904
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800905status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700906 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800907 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700908 return BAD_VALUE;
909 }
910
911 // FIXME for now we always return stats for the primary display
912 memset(stats, 0, sizeof(*stats));
913 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
914 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
915 return NO_ERROR;
916}
917
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700918int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800919 if (display == nullptr) {
920 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800921 return BAD_VALUE;
922 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700923
924 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800925 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700926 return device->getActiveConfig();
927 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700928
Dan Stoza24a42e92015-03-09 10:04:11 -0700929 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700930}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700931
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700932void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
933 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
934 this);
935 int32_t type = hw->getDisplayType();
936 int currentMode = hw->getActiveConfig();
937
938 if (mode == currentMode) {
939 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
940 return;
941 }
942
943 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
944 ALOGW("Trying to set config for virtual display");
945 return;
946 }
947
948 hw->setActiveConfig(mode);
949 getHwComposer().setActiveConfig(type, mode);
950}
951
952status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
953 class MessageSetActiveConfig: public MessageBase {
954 SurfaceFlinger& mFlinger;
955 sp<IBinder> mDisplay;
956 int mMode;
957 public:
958 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
959 int mode) :
960 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
961 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700962 Vector<DisplayInfo> configs;
963 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700964 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700965 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700966 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700967 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700968 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700969 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800970 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700971 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700972 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700973 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
974 ALOGW("Attempt to set active config = %d for virtual display",
975 mMode);
976 } else {
977 mFlinger.setActiveConfigInternal(hw, mMode);
978 }
979 return true;
980 }
981 };
982 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
983 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700984 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700985}
Michael Wright28f24d02016-07-12 13:30:53 -0700986status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -0700987 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700988 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
989 return BAD_VALUE;
990 }
991
992 if (!display.get()) {
993 return NAME_NOT_FOUND;
994 }
995
996 int32_t type = NAME_NOT_FOUND;
997 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
998 if (display == mBuiltinDisplays[i]) {
999 type = i;
1000 break;
1001 }
1002 }
1003
1004 if (type < 0) {
1005 return type;
1006 }
1007
Peiyong Lina52f0292018-03-14 17:26:31 -07001008 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001009 {
1010 ConditionalLock _l(mStateLock,
1011 std::this_thread::get_id() != mMainThreadId);
1012 modes = getHwComposer().getColorModes(type);
1013 }
Michael Wright28f24d02016-07-12 13:30:53 -07001014 outColorModes->clear();
1015 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1016
1017 return NO_ERROR;
1018}
1019
Peiyong Lina52f0292018-03-14 17:26:31 -07001020ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001021 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -07001022 if (device != nullptr) {
1023 return device->getActiveColorMode();
1024 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001025 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001026}
1027
1028void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001029 ColorMode mode, Dataspace dataSpace,
1030 RenderIntent renderIntent) {
Michael Wright28f24d02016-07-12 13:30:53 -07001031 int32_t type = hw->getDisplayType();
Peiyong Lina52f0292018-03-14 17:26:31 -07001032 ColorMode currentMode = hw->getActiveColorMode();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001033 Dataspace currentDataSpace = hw->getCompositionDataSpace();
Peiyong Lin38e9a562018-04-10 16:24:20 -07001034 RenderIntent currentRenderIntent = hw->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001035
Peiyong Lin38e9a562018-04-10 16:24:20 -07001036 if (mode == currentMode && dataSpace == currentDataSpace &&
1037 renderIntent == currentRenderIntent) {
1038 return;
1039 }
1040
1041 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1042 ALOGW("Trying to set config for virtual display");
1043 return;
1044 }
1045
1046 hw->setActiveColorMode(mode);
1047 hw->setCompositionDataSpace(dataSpace);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001048 hw->setActiveRenderIntent(renderIntent);
1049 getHwComposer().setActiveColorMode(type, mode, renderIntent);
1050
1051 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
1052 decodeColorMode(mode).c_str(), mode,
1053 decodeRenderIntent(renderIntent).c_str(), renderIntent,
1054 hw->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001055}
1056
1057
1058status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001059 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -07001060 class MessageSetActiveColorMode: public MessageBase {
1061 SurfaceFlinger& mFlinger;
1062 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -07001063 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001064 public:
1065 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -07001066 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -07001067 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1068 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -07001069 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001070 mFlinger.getDisplayColorModes(mDisplay, &modes);
1071 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -07001072 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001073 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1074 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001075 return true;
1076 }
1077 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1078 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001079 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1080 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001081 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001082 ALOGW("Attempt to set active color mode %s %d for virtual display",
1083 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001084 } else {
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001085 mFlinger.setActiveColorModeInternal(hw, mMode, Dataspace::UNKNOWN,
1086 RenderIntent::COLORIMETRIC);
Michael Wright28f24d02016-07-12 13:30:53 -07001087 }
1088 return true;
1089 }
1090 };
1091 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1092 postMessageSync(msg);
1093 return NO_ERROR;
1094}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001095
Svetoslavd85084b2014-03-20 10:28:31 -07001096status_t SurfaceFlinger::clearAnimationFrameStats() {
1097 Mutex::Autolock _l(mStateLock);
1098 mAnimFrameTracker.clearStats();
1099 return NO_ERROR;
1100}
1101
1102status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1103 Mutex::Autolock _l(mStateLock);
1104 mAnimFrameTracker.getStats(outStats);
1105 return NO_ERROR;
1106}
1107
Dan Stozac4f471e2016-03-24 09:31:08 -07001108status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1109 HdrCapabilities* outCapabilities) const {
1110 Mutex::Autolock _l(mStateLock);
1111
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001112 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001113 if (displayDevice == nullptr) {
1114 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1115 return BAD_VALUE;
1116 }
1117
Peiyong Linfb069302018-04-25 14:34:31 -07001118 // At this point the DisplayDeivce should already be set up,
1119 // meaning the luminance information is already queried from
1120 // hardware composer and stored properly.
1121 const HdrCapabilities& capabilities = displayDevice->getHdrCapabilities();
1122 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1123 capabilities.getDesiredMaxLuminance(),
1124 capabilities.getDesiredMaxAverageLuminance(),
1125 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001126
1127 return NO_ERROR;
1128}
1129
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001130status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001131 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1132 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001133
Chia-I Wu90f669f2017-10-05 14:24:41 -07001134 if (mInjectVSyncs == enable) {
1135 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001136 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001137
1138 if (enable) {
1139 ALOGV("VSync Injections enabled");
1140 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001141 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001142 mInjectorEventThread = std::make_unique<
1143 impl::EventThread>(mVSyncInjector.get(),
1144 [this]() { resyncWithRateLimit(); },
1145 impl::EventThread::InterceptVSyncsCallback(),
1146 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001147 }
Lloyd Pique9123ae52018-01-22 17:14:00 -08001148 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001149 } else {
1150 ALOGV("VSync Injections disabled");
Lloyd Pique9123ae52018-01-22 17:14:00 -08001151 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001152 }
1153
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001154 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001155 });
1156 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001157 return NO_ERROR;
1158}
1159
1160status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001161 Mutex::Autolock _l(mStateLock);
1162
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001163 if (!mInjectVSyncs) {
1164 ALOGE("VSync Injections not enabled");
1165 return BAD_VALUE;
1166 }
1167 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1168 ALOGV("Injecting VSync inside SurfaceFlinger");
1169 mVSyncInjector->onInjectSyncEvent(when);
1170 }
1171 return NO_ERROR;
1172}
1173
Lloyd Pique755e3192018-01-31 16:46:15 -08001174status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1175 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001176 IPCThreadState* ipc = IPCThreadState::self();
1177 const int pid = ipc->getCallingPid();
1178 const int uid = ipc->getCallingUid();
1179 if ((uid != AID_SHELL) &&
1180 !PermissionCache::checkPermission(sDump, pid, uid)) {
1181 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1182 return PERMISSION_DENIED;
1183 }
1184
1185 // Try to acquire a lock for 1s, fail gracefully
1186 const status_t err = mStateLock.timedLock(s2ns(1));
1187 const bool locked = (err == NO_ERROR);
1188 if (!locked) {
1189 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1190 return TIMED_OUT;
1191 }
1192
1193 outLayers->clear();
1194 mCurrentState.traverseInZOrder([&](Layer* layer) {
1195 outLayers->push_back(layer->getLayerDebugInfo());
1196 });
1197
1198 mStateLock.unlock();
1199 return NO_ERROR;
1200}
1201
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001202// ----------------------------------------------------------------------------
1203
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001204sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1205 ISurfaceComposer::VsyncSource vsyncSource) {
1206 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1207 return mSFEventThread->createEventConnection();
1208 } else {
1209 return mEventThread->createEventConnection();
1210 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001211}
1212
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001213// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001214
1215void SurfaceFlinger::waitForEvent() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001216 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001217}
1218
1219void SurfaceFlinger::signalTransaction() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001220 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001221}
1222
1223void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001224 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001225}
1226
1227void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001228 mRefreshPending = true;
Lloyd Pique9123ae52018-01-22 17:14:00 -08001229 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001230}
1231
1232status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001233 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001234 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001235}
1236
1237status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001238 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001239 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001240 if (res == NO_ERROR) {
1241 msg->wait();
1242 }
1243 return res;
1244}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001245
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001246void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001247 do {
1248 waitForEvent();
1249 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001250}
1251
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001252void SurfaceFlinger::enableHardwareVsync() {
1253 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001254 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001255 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001256 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1257 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001258 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001259 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001260}
1261
Jesse Hall948fe0c2013-10-14 12:56:09 -07001262void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001263 Mutex::Autolock _l(mHWVsyncLock);
1264
Jesse Hall948fe0c2013-10-14 12:56:09 -07001265 if (makeAvailable) {
1266 mHWVsyncAvailable = true;
1267 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001268 // Hardware vsync is not currently available, so abort the resync
1269 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001270 return;
1271 }
1272
David Sodman105b7dc2017-11-04 20:28:14 -07001273 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001274 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001275
1276 mPrimaryDispSync.reset();
1277 mPrimaryDispSync.setPeriod(period);
1278
1279 if (!mPrimaryHWVsyncEnabled) {
1280 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001281 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1282 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001283 mPrimaryHWVsyncEnabled = true;
1284 }
1285}
1286
Jesse Hall948fe0c2013-10-14 12:56:09 -07001287void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001288 Mutex::Autolock _l(mHWVsyncLock);
1289 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001290 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1291 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001292 mPrimaryDispSync.endResync();
1293 mPrimaryHWVsyncEnabled = false;
1294 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001295 if (makeUnavailable) {
1296 mHWVsyncAvailable = false;
1297 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001298}
1299
Tim Murray4a4e4a22016-04-19 16:29:23 +00001300void SurfaceFlinger::resyncWithRateLimit() {
1301 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001302
1303 // No explicit locking is needed here since EventThread holds a lock while calling this method
1304 static nsecs_t sLastResyncAttempted = 0;
1305 const nsecs_t now = systemTime();
1306 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001307 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001308 }
Dan Stoza57164302017-05-08 14:03:54 -07001309 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001310}
1311
Steven Thomasb02664d2017-07-26 18:48:28 -07001312void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1313 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001314 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001315 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001316 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001317 return;
1318 }
1319
1320 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001321 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001322 return;
1323 }
1324
Jamie Gennisd1700752013-10-14 12:22:52 -07001325 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001326
Jamie Gennisd1700752013-10-14 12:22:52 -07001327 { // Scope for the lock
1328 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001329 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001330 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001331 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001332 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001333
1334 if (needsHwVsync) {
1335 enableHardwareVsync();
1336 } else {
1337 disableHardwareVsync(false);
1338 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001339}
1340
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001341void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001342 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1343 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001344}
1345
Lloyd Pique715a2c12017-12-14 17:18:08 -08001346void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1347 HWC2::Connection connection) {
1348 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1349 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001350
Lloyd Piqueba04e622017-12-14 17:11:26 -08001351 // Ignore events that do not have the right sequenceId.
1352 if (sequenceId != getBE().mComposerSequenceId) {
1353 return;
1354 }
1355
Steven Thomasb02664d2017-07-26 18:48:28 -07001356 // Only lock if we're not on the main thread. This function is normally
1357 // called on a hwbinder thread, but for the primary display it's called on
1358 // the main thread with the state lock already held, so don't attempt to
1359 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001360 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001361
Lloyd Pique715a2c12017-12-14 17:18:08 -08001362 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001363
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001364 if (std::this_thread::get_id() == mMainThreadId) {
1365 // Process all pending hot plug events immediately if we are on the main thread.
1366 processDisplayHotplugEventsLocked();
1367 }
1368
Lloyd Piqueba04e622017-12-14 17:11:26 -08001369 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001370}
1371
Steven Thomasb02664d2017-07-26 18:48:28 -07001372void SurfaceFlinger::onRefreshReceived(int sequenceId,
1373 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001374 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001375 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001376 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001377 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001378 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001379}
1380
Dan Stoza9e56aa02015-11-02 13:00:03 -08001381void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001382 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001383 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001384 getHwComposer().setVsyncEnabled(disp,
1385 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001386}
1387
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001388// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001389void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001390 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001391 // Clear the drawing state so that the logic inside of
1392 // handleTransactionLocked will fire. It will determine the delta between
1393 // mCurrentState and mDrawingState and re-apply all changes when we make the
1394 // transition.
1395 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001396 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001397 mDisplays.clear();
1398}
1399
Steven Thomas050b2c82017-03-06 11:45:16 -08001400void SurfaceFlinger::updateVrFlinger() {
1401 if (!mVrFlinger)
1402 return;
1403 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001404 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001405 return;
1406 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001407
David Sodman105b7dc2017-11-04 20:28:14 -07001408 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001409 ALOGE("Vr flinger is only supported for remote hardware composer"
1410 " service connections. Ignoring request to transition to vr"
1411 " flinger.");
1412 mVrFlingerRequestsDisplay = false;
1413 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001414 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001415
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001416 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001417
Steven Thomasb02664d2017-07-26 18:48:28 -07001418 int currentDisplayPowerMode = getDisplayDeviceLocked(
1419 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001420
Steven Thomasb02664d2017-07-26 18:48:28 -07001421 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001422 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001423 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001424
Steven Thomasb02664d2017-07-26 18:48:28 -07001425 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001426 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001427 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1428 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001429 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001430
David Sodman105b7dc2017-11-04 20:28:14 -07001431 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1432 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001433
1434 if (vrFlingerRequestsDisplay) {
1435 mVrFlinger->GrantDisplayOwnership();
1436 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001437 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001438 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001439
1440 mVisibleRegionsDirty = true;
1441 invalidateHwcGeometry();
1442
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001443 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001444 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1445 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1446 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001447
Steven Thomasb02664d2017-07-26 18:48:28 -07001448 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001449 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001450 const nsecs_t period = activeConfig->getVsyncPeriod();
1451 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001452
Steven Thomasb02664d2017-07-26 18:48:28 -07001453 // Use phase of 0 since phase is not known.
1454 // Use latency of 0, which will snap to the ideal latency.
1455 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001456
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001457 android_atomic_or(1, &mRepaintEverything);
1458 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001459}
1460
Mathias Agopian4fec8732012-06-29 14:12:52 -07001461void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001462 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001463 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001464 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001465 bool frameMissed = !mHadClientComposition &&
1466 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001467 (mPreviousPresentFence->getSignalTime() ==
1468 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001469 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001470 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001471 mTimeStats.incrementMissedFrames();
1472 if (mPropagateBackpressure) {
1473 signalLayerUpdate();
1474 break;
1475 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001476 }
Dan Stoza50182882016-07-08 12:02:20 -07001477
Steven Thomas050b2c82017-03-06 11:45:16 -08001478 // Now that we're going to make it to the handleMessageTransaction()
1479 // call below it's safe to call updateVrFlinger(), which will
1480 // potentially trigger a display handoff.
1481 updateVrFlinger();
1482
Dan Stoza6b9454d2014-11-07 16:00:59 -08001483 bool refreshNeeded = handleMessageTransaction();
1484 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001485 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001486 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001487 // Signal a refresh if a transaction modified the window state,
1488 // a new buffer was latched, or if HWC has requested a full
1489 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001490 signalRefresh();
1491 }
1492 break;
1493 }
1494 case MessageQueue::REFRESH: {
1495 handleMessageRefresh();
1496 break;
1497 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001498 }
1499}
1500
Dan Stoza6b9454d2014-11-07 16:00:59 -08001501bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001502 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001503 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001504 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001505 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001506 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001507 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001508}
1509
Dan Stoza6b9454d2014-11-07 16:00:59 -08001510bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001511 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001512 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001513}
1514
1515void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001516 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001517
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001518 mRefreshPending = false;
1519
Pablo Ceballos40845df2016-01-25 17:41:15 -08001520 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001521
Brian Andersond6927fb2016-07-23 23:37:30 -07001522 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001523 rebuildLayerStacks();
1524 setUpHWComposer();
1525 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001526 doTracing("handleRefresh");
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001527 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001528 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001529 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001530
David Sodman105b7dc2017-11-04 20:28:14 -07001531 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001532
1533 mHadClientComposition = false;
1534 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1535 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1536 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001537 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001538 }
Dan Stoza2713c302018-03-28 17:07:36 -07001539 mVsyncModulator.setLastFrameUsedRenderEngine(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001540
Dan Stoza9e56aa02015-11-02 13:00:03 -08001541 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001542}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001543
Mathias Agopiancd60f992012-08-16 16:28:27 -07001544void SurfaceFlinger::doDebugFlashRegions()
1545{
1546 // is debugging enabled
1547 if (CC_LIKELY(!mDebugRegion))
1548 return;
1549
1550 const bool repaintEverything = mRepaintEverything;
1551 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1552 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001553 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001554 // transform the dirty region into this screen's coordinate space
1555 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1556 if (!dirtyRegion.isEmpty()) {
1557 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001558 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001559
1560 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001561 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001562 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001563 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1564
Mathias Agopianda27af92012-09-13 18:17:13 -07001565 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001566 }
1567 }
1568 }
1569
1570 postFramebuffer();
1571
1572 if (mDebugRegion > 1) {
1573 usleep(mDebugRegion * 1000);
1574 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001575
Dan Stoza9e56aa02015-11-02 13:00:03 -08001576 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001577 auto& displayDevice = mDisplays[displayId];
1578 if (!displayDevice->isDisplayOn()) {
1579 continue;
1580 }
1581
David Sodman105b7dc2017-11-04 20:28:14 -07001582 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1583 ALOGE_IF(result != NO_ERROR,
1584 "prepareFrame for display %zd failed:"
1585 " %d (%s)",
1586 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001587 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001588}
1589
Adrian Roos1e1a1282017-11-01 19:05:31 +01001590void SurfaceFlinger::doTracing(const char* where) {
1591 ATRACE_CALL();
1592 ATRACE_NAME(where);
1593 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001594 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001595 }
1596}
1597
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001598void SurfaceFlinger::logLayerStats() {
1599 ATRACE_CALL();
1600 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1601 int32_t hwcId = -1;
1602 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1603 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1604 if (displayDevice->isPrimary()) {
1605 hwcId = displayDevice->getHwcDisplayId();
1606 break;
1607 }
1608 }
1609 if (hwcId < 0) {
1610 ALOGE("LayerStats: Hmmm, no primary display?");
1611 return;
1612 }
1613 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1614 }
1615}
1616
Brian Andersond6927fb2016-07-23 23:37:30 -07001617void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001618{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001619 ATRACE_CALL();
1620 ALOGV("preComposition");
1621
Mathias Agopiancd60f992012-08-16 16:28:27 -07001622 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001623 mDrawingState.traverseInZOrder([&](Layer* layer) {
1624 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001625 needExtraInvalidate = true;
1626 }
Robert Carr2047fae2016-11-28 14:09:09 -08001627 });
1628
Mathias Agopiancd60f992012-08-16 16:28:27 -07001629 if (needExtraInvalidate) {
1630 signalLayerUpdate();
1631 }
1632}
1633
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001634void SurfaceFlinger::updateCompositorTiming(
1635 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1636 std::shared_ptr<FenceTime>& presentFenceTime) {
1637 // Update queue of past composite+present times and determine the
1638 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001639 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001640 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001641 while (!getBE().mCompositePresentTimes.empty()) {
1642 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001643 // Cached values should have been updated before calling this method,
1644 // which helps avoid duplicate syscalls.
1645 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1646 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1647 break;
1648 }
1649 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001650 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001651 }
1652
1653 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001654 while (getBE().mCompositePresentTimes.size() > 16) {
1655 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001656 }
1657
Brian Andersond0010582017-03-07 13:20:31 -08001658 setCompositorTimingSnapped(
1659 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1660}
1661
1662void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1663 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001664 // Integer division and modulo round toward 0 not -inf, so we need to
1665 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001666 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001667 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1668 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1669
Brian Andersond0010582017-03-07 13:20:31 -08001670 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1671 if (idealLatency <= 0) {
1672 idealLatency = vsyncInterval;
1673 }
1674
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001675 // Snap the latency to a value that removes scheduling jitter from the
1676 // composition and present times, which often have >1ms of jitter.
1677 // Reducing jitter is important if an app attempts to extrapolate
1678 // something (such as user input) to an accurate diasplay time.
1679 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1680 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001681 nsecs_t bias = vsyncInterval / 2;
1682 int64_t extraVsyncs =
1683 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1684 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1685 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001686
David Sodman99974d22017-11-28 12:04:33 -08001687 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1688 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1689 getBE().mCompositorTiming.interval = vsyncInterval;
1690 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001691}
1692
1693void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001694{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001695 ATRACE_CALL();
1696 ALOGV("postComposition");
1697
Brian Anderson3546a3f2016-07-14 11:51:14 -07001698 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001699 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001700 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001701 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001702 }
1703
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001704 // |mStateLock| not needed as we are on the main thread
1705 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001706
David Sodman73beded2017-11-15 11:56:06 -08001707 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001708 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001709 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001710 glCompositionDoneFenceTime =
1711 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001712 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001713 } else {
1714 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1715 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001716
David Sodman73beded2017-11-15 11:56:06 -08001717 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001718 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001719 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001720 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001721
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001722 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1723 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1724
1725 // We use the refreshStartTime which might be sampled a little later than
1726 // when we started doing work for this frame, but that should be okay
1727 // since updateCompositorTiming has snapping logic.
1728 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001729 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001730 CompositorTiming compositorTiming;
1731 {
David Sodman99974d22017-11-28 12:04:33 -08001732 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1733 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001734 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001735
Robert Carr2047fae2016-11-28 14:09:09 -08001736 mDrawingState.traverseInZOrder([&](Layer* layer) {
1737 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001738 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001739 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001740 recordBufferingStats(layer->getName().string(),
1741 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001742 }
Robert Carr2047fae2016-11-28 14:09:09 -08001743 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001744
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001745 if (presentFenceTime->isValid()) {
1746 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001747 enableHardwareVsync();
1748 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001749 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001750 }
1751 }
1752
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001753 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001754 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001755 enableHardwareVsync();
1756 }
1757 }
1758
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001759 if (mAnimCompositionPending) {
1760 mAnimCompositionPending = false;
1761
Brian Anderson4e606e32017-03-16 15:34:57 -07001762 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001763 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001764 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001765 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001766 // The HWC doesn't support present fences, so use the refresh
1767 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001768 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001769 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001770 mAnimFrameTracker.setActualPresentTime(presentTime);
1771 }
1772 mAnimFrameTracker.advanceFrame();
1773 }
Dan Stozab90cf072015-03-05 11:05:59 -08001774
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001775 mTimeStats.incrementTotalFrames();
1776 if (mHadClientComposition) {
1777 mTimeStats.incrementClientCompositionFrames();
1778 }
1779
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001780 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1781 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001782 return;
1783 }
1784
1785 nsecs_t currentTime = systemTime();
1786 if (mHasPoweredOff) {
1787 mHasPoweredOff = false;
1788 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001789 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001790 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001791 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1792 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001793 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001794 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001795 }
David Sodman4a36e932017-11-07 14:29:47 -08001796 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001797 }
David Sodman4a36e932017-11-07 14:29:47 -08001798 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001799}
1800
1801void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001802 ATRACE_CALL();
1803 ALOGV("rebuildLayerStacks");
1804
Mathias Agopiancd60f992012-08-16 16:28:27 -07001805 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001806 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001807 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001808 mVisibleRegionsDirty = false;
1809 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001810
Jeff Sharkey76488112017-02-27 14:15:18 -07001811 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1812 Region opaqueRegion;
1813 Region dirtyRegion;
1814 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001815 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001816 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1817 const Transform& tr(displayDevice->getTransform());
1818 const Rect bounds(displayDevice->getBounds());
1819 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001820 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001821
Jeff Sharkey76488112017-02-27 14:15:18 -07001822 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001823 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001824 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1825 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001826 Region drawRegion(tr.transform(
1827 layer->visibleNonTransparentRegion));
1828 drawRegion.andSelf(bounds);
1829 if (!drawRegion.isEmpty()) {
1830 layersSortedByZ.add(layer);
1831 } else {
1832 // Clear out the HWC layer if this layer was
1833 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001834 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001835 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001836 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001837 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001838 // WM changes displayDevice->layerStack upon sleep/awake.
1839 // Here we make sure we delete the HWC layers even if
1840 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001841 hwcLayerDestroyed = layer->destroyHwcLayer(
1842 displayDevice->getHwcDisplayId());
1843 }
1844
1845 // If a layer is not going to get a release fence because
1846 // it is invisible, but it is also going to release its
1847 // old buffer, add it to the list of layers needing
1848 // fences.
1849 if (hwcLayerDestroyed) {
1850 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1851 mLayersWithQueuedFrames.cend(), layer);
1852 if (found != mLayersWithQueuedFrames.cend()) {
1853 layersNeedingFences.add(layer);
1854 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001855 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001856 });
1857 }
1858 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001859 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001860 displayDevice->undefinedRegion.set(bounds);
1861 displayDevice->undefinedRegion.subtractSelf(
1862 tr.transform(opaqueRegion));
1863 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001864 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001865 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001866}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001867
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001868// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001869// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001870// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001871// - Dataspace::DISPLAY_P3
1872// - Dataspace::V0_SCRGB_LINEAR
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001873// The returned HDR data space is one of
1874// - Dataspace::UNKNOWN
1875// - Dataspace::BT2020_HLG
1876// - Dataspace::BT2020_PQ
1877Dataspace SurfaceFlinger::getBestDataspace(
1878 const sp<const DisplayDevice>& displayDevice, Dataspace* outHdrDataSpace) const {
1879 Dataspace bestDataSpace = Dataspace::SRGB;
1880 *outHdrDataSpace = Dataspace::UNKNOWN;
1881
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001882 for (const auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1883 switch (layer->getDataSpace()) {
1884 case Dataspace::V0_SCRGB:
1885 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001886 bestDataSpace = Dataspace::V0_SCRGB_LINEAR;
Peiyong Linf59a7192018-04-25 11:19:31 -07001887 break;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001888 case Dataspace::DISPLAY_P3:
1889 if (bestDataSpace == Dataspace::SRGB) {
1890 bestDataSpace = Dataspace::DISPLAY_P3;
1891 }
1892 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001893 case Dataspace::BT2020_PQ:
1894 case Dataspace::BT2020_ITU_PQ:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001895 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001896 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001897 case Dataspace::BT2020_HLG:
1898 case Dataspace::BT2020_ITU_HLG:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001899 // When there's mixed PQ content and HLG content, we set the HDR
1900 // data space to be BT2020_PQ and convert HLG to PQ.
1901 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1902 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001903 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001904 break;
1905 default:
1906 break;
1907 }
Romain Guy54f154a2017-10-24 21:40:32 +01001908 }
1909
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001910 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001911}
1912
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001913// Pick the ColorMode / Dataspace for the display device.
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001914void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& displayDevice,
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001915 ColorMode* outMode, Dataspace* outDataSpace,
1916 RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001917 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1918 *outMode = ColorMode::NATIVE;
1919 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001920 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001921 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001922 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001923
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001924 Dataspace hdrDataSpace;
1925 Dataspace bestDataSpace = getBestDataspace(displayDevice, &hdrDataSpace);
1926
1927 if (hdrDataSpace == Dataspace::BT2020_PQ) {
1928 // Hardware composer can handle BT2100 ColorMode only when
1929 // - colorimetrical tone mapping is supported, or
1930 // - Auto mode is turned on and enhanced tone mapping is supported.
1931 if (displayDevice->hasBT2100PQColorimetricSupport() ||
1932 (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
1933 displayDevice->hasBT2100PQEnhanceSupport())) {
1934 *outMode = ColorMode::BT2100_PQ;
1935 *outDataSpace = Dataspace::BT2020_PQ;
1936 } else if (displayDevice->hasHDR10Support()) {
1937 // Legacy HDR support. HDR layers are treated as UNKNOWN layers.
1938 hdrDataSpace = Dataspace::UNKNOWN;
1939 } else {
1940 // Simulate PQ through RenderEngine, pick DISPLAY_P3 color mode.
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001941 *outMode = ColorMode::DISPLAY_P3;
1942 *outDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001943 }
1944 } else if (hdrDataSpace == Dataspace::BT2020_HLG) {
1945 if (displayDevice->hasBT2100HLGColorimetricSupport() ||
1946 (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
1947 displayDevice->hasBT2100HLGEnhanceSupport())) {
1948 *outMode = ColorMode::BT2100_HLG;
1949 *outDataSpace = Dataspace::BT2020_HLG;
1950 } else if (displayDevice->hasHLGSupport()) {
1951 // Legacy HDR support. HDR layers are treated as UNKNOWN layers.
1952 hdrDataSpace = Dataspace::UNKNOWN;
1953 } else {
1954 // Simulate HLG through RenderEngine, pick DISPLAY_P3 color mode.
1955 *outMode = ColorMode::DISPLAY_P3;
1956 *outDataSpace = Dataspace::DISPLAY_P3;
1957 }
1958 }
1959
1960 // At this point, there's no HDR layer.
1961 if (hdrDataSpace == Dataspace::UNKNOWN) {
1962 switch (bestDataSpace) {
1963 case Dataspace::DISPLAY_P3:
1964 case Dataspace::V0_SCRGB_LINEAR:
1965 *outMode = ColorMode::DISPLAY_P3;
1966 *outDataSpace = Dataspace::DISPLAY_P3;
1967 break;
1968 default:
1969 *outMode = ColorMode::SRGB;
1970 *outDataSpace = Dataspace::SRGB;
1971 break;
1972 }
1973 }
1974 *outRenderIntent = pickRenderIntent(displayDevice, *outMode);
1975}
1976
1977RenderIntent SurfaceFlinger::pickRenderIntent(const sp<DisplayDevice>& displayDevice,
1978 ColorMode colorMode) const {
1979 // Native Mode means the display is not color managed, and whichever
1980 // render intent is picked doesn't matter, thus return
1981 // RenderIntent::COLORIMETRIC as default here.
1982 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1983 return RenderIntent::COLORIMETRIC;
1984 }
1985
1986 // In Auto Color Mode, we want to strech to panel color space, right now
1987 // only the built-in display supports it.
1988 if (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
1989 mBuiltinDisplaySupportsEnhance &&
1990 displayDevice->getDisplayType() == DisplayDevice::DISPLAY_PRIMARY) {
1991 switch (colorMode) {
1992 case ColorMode::DISPLAY_P3:
1993 case ColorMode::SRGB:
1994 return RenderIntent::ENHANCE;
1995 // In Auto Color Mode, BT2100_PQ and BT2100_HLG will only be picked
1996 // when TONE_MAP_ENHANCE or TONE_MAP_COLORIMETRIC is supported.
1997 // If TONE_MAP_ENHANCE is not supported, fall back to TONE_MAP_COLORIMETRIC.
1998 case ColorMode::BT2100_PQ:
1999 return displayDevice->hasBT2100PQEnhanceSupport() ?
2000 RenderIntent::TONE_MAP_ENHANCE : RenderIntent::TONE_MAP_COLORIMETRIC;
2001 case ColorMode::BT2100_HLG:
2002 return displayDevice->hasBT2100HLGEnhanceSupport() ?
2003 RenderIntent::TONE_MAP_ENHANCE : RenderIntent::TONE_MAP_COLORIMETRIC;
2004 // This statement shouldn't be reached, switch cases will always
2005 // cover all possible ColorMode returned by pickColorMode.
2006 default:
2007 return RenderIntent::COLORIMETRIC;
2008 }
2009 }
2010
2011 // Either enhance is not supported or we are in natural mode.
2012
2013 // Natural Mode means it's color managed and the color must be right,
2014 // thus we pick RenderIntent::COLORIMETRIC as render intent for non-HDR
2015 // content and pick RenderIntent::TONE_MAP_COLORIMETRIC for HDR content.
2016 switch (colorMode) {
2017 // In Natural Color Mode, BT2100_PQ and BT2100_HLG will only be picked
2018 // when TONE_MAP_COLORIMETRIC is supported.
2019 case ColorMode::BT2100_PQ:
2020 case ColorMode::BT2100_HLG:
2021 return RenderIntent::TONE_MAP_COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002022 default:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002023 return RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002024 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002025}
2026
Mathias Agopiancd60f992012-08-16 16:28:27 -07002027void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002028 ATRACE_CALL();
2029 ALOGV("setUpHWComposer");
2030
Jesse Hall028dc8f2013-08-20 16:35:32 -07002031 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Dan Stozac7a25ad2018-04-12 11:45:09 -07002032 bool dirty = !mDisplays[dpy]->getDirtyRegion(mRepaintEverything).isEmpty();
Jesse Hallb7a05492014-08-14 15:45:06 -07002033 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
2034 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
2035
2036 // If nothing has changed (!dirty), don't recompose.
2037 // If something changed, but we don't currently have any visible layers,
2038 // and didn't when we last did a composition, then skip it this time.
2039 // The second rule does two things:
2040 // - When all layers are removed from a display, we'll emit one black
2041 // frame, then nothing more until we get new layers.
2042 // - When a display is created with a private layer stack, we won't
2043 // emit any black frames until a layer is added to the layer stack.
2044 bool mustRecompose = dirty && !(empty && wasEmpty);
2045
2046 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2047 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
2048 mustRecompose ? "doing" : "skipping",
2049 dirty ? "+" : "-",
2050 empty ? "+" : "-",
2051 wasEmpty ? "+" : "-");
2052
Dan Stoza71433162014-02-04 16:22:36 -08002053 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07002054
2055 if (mustRecompose) {
2056 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
2057 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07002058 }
2059
Dan Stoza9e56aa02015-11-02 13:00:03 -08002060 // build the h/w work list
2061 if (CC_UNLIKELY(mGeometryInvalid)) {
2062 mGeometryInvalid = false;
2063 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2064 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
2065 const auto hwcId = displayDevice->getHwcDisplayId();
2066 if (hwcId >= 0) {
2067 const Vector<sp<Layer>>& currentLayers(
2068 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08002069 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002070 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08002071 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07002072 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002073 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002074 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07002075 }
2076 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07002077
Robert Carrae060832016-11-28 10:51:00 -08002078 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002079 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002080 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07002081 }
2082 }
2083 }
2084 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002085 }
Riley Andrews03414a12014-07-01 14:22:59 -07002086
Dan Stoza9e56aa02015-11-02 13:00:03 -08002087 // Set the per-frame data
2088 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2089 auto& displayDevice = mDisplays[displayId];
2090 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002091
Dan Stoza9e56aa02015-11-02 13:00:03 -08002092 if (hwcId < 0) {
2093 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07002094 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07002095 if (mDrawingState.colorMatrixChanged) {
2096 displayDevice->setColorTransform(mDrawingState.colorMatrix);
2097 status_t result = getBE().mHwc->setColorTransform(hwcId, mDrawingState.colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002098 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
2099 "display %zd: %d", displayId, result);
2100 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002101 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002102 if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2103 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Peiyong Lin62665892018-04-16 11:07:44 -07002104 !displayDevice->hasHDR10Support()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002105 layer->forceClientComposition(hwcId);
2106 }
Peiyong Linf59a7192018-04-25 11:19:31 -07002107 if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
2108 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
2109 !displayDevice->hasHLGSupport()) {
2110 layer->forceClientComposition(hwcId);
2111 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002112
chaviwc9232ed2017-11-14 15:31:15 -08002113 if (layer->getForceClientComposition(hwcId)) {
2114 ALOGV("[%s] Requesting Client composition", layer->getName().string());
2115 layer->setCompositionType(hwcId, HWC2::Composition::Client);
2116 continue;
2117 }
2118
Dan Stoza9e56aa02015-11-02 13:00:03 -08002119 layer->setPerFrameData(displayDevice);
2120 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002121
2122 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002123 ColorMode colorMode;
2124 Dataspace dataSpace;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002125 RenderIntent renderIntent;
2126 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
2127 setActiveColorModeInternal(displayDevice, colorMode, dataSpace, renderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002128 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002129 }
2130
Chia-I Wu28f320b2018-05-03 11:02:56 -07002131 mDrawingState.colorMatrixChanged = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002132
Dan Stoza9e56aa02015-11-02 13:00:03 -08002133 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002134 auto& displayDevice = mDisplays[displayId];
2135 if (!displayDevice->isDisplayOn()) {
2136 continue;
2137 }
2138
David Sodman105b7dc2017-11-04 20:28:14 -07002139 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002140 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2141 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002142 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002143}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002144
Mathias Agopiancd60f992012-08-16 16:28:27 -07002145void SurfaceFlinger::doComposition() {
2146 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002147 ALOGV("doComposition");
2148
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002149 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002150 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002151 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002152 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002153 // transform the dirty region into this screen's coordinate space
2154 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002155
2156 // repaint the framebuffer (if needed)
2157 doDisplayComposition(hw, dirtyRegion);
2158
Mathias Agopiancd60f992012-08-16 16:28:27 -07002159 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002160 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002161 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002162 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002163 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002164}
2165
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002166void SurfaceFlinger::postFramebuffer()
2167{
Mathias Agopian841cde52012-03-01 15:44:37 -08002168 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002169 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002170
Mathias Agopiana44b0412011-10-16 18:46:35 -07002171 const nsecs_t now = systemTime();
2172 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002173
Dan Stoza9e56aa02015-11-02 13:00:03 -08002174 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2175 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002176 if (!displayDevice->isDisplayOn()) {
2177 continue;
2178 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002179 const auto hwcId = displayDevice->getHwcDisplayId();
2180 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002181 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002182 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002183 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002184 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002185 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002186 // The layer buffer from the previous frame (if any) is released
2187 // by HWC only when the release fence from this frame (if any) is
2188 // signaled. Always get the release fence from HWC first.
2189 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002190 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002191
2192 // If the layer was client composited in the previous frame, we
2193 // need to merge with the previous client target acquire fence.
2194 // Since we do not track that, always merge with the current
2195 // client target acquire fence when it is available, even though
2196 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002197 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002198 releaseFence = Fence::merge("LayerRelease", releaseFence,
2199 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002200 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002201
Dan Stoza9e56aa02015-11-02 13:00:03 -08002202 layer->onLayerDisplayed(releaseFence);
2203 }
Chia-I Wu83806892017-11-16 10:50:20 -08002204
2205 // We've got a list of layers needing fences, that are disjoint with
2206 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2207 // supply them with the present fence.
2208 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002209 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002210 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2211 layer->onLayerDisplayed(presentFence);
2212 }
2213 }
2214
Dan Stoza9e56aa02015-11-02 13:00:03 -08002215 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002216 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002217 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002218 }
2219
Mathias Agopiana44b0412011-10-16 18:46:35 -07002220 mLastSwapBufferTime = systemTime() - now;
2221 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002222
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002223 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002224 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2225 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2226 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2227 logFrameStats();
2228 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002229 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002230}
2231
Mathias Agopian87baae12012-07-31 12:38:26 -07002232void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002233{
Mathias Agopian841cde52012-03-01 15:44:37 -08002234 ATRACE_CALL();
2235
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002236 // here we keep a copy of the drawing state (that is the state that's
2237 // going to be overwritten by handleTransactionLocked()) outside of
2238 // mStateLock so that the side-effects of the State assignment
2239 // don't happen with mStateLock held (which can cause deadlocks).
2240 State drawingState(mDrawingState);
2241
Mathias Agopianca4d3602011-05-19 15:38:14 -07002242 Mutex::Autolock _l(mStateLock);
2243 const nsecs_t now = systemTime();
2244 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002245
Mathias Agopianca4d3602011-05-19 15:38:14 -07002246 // Here we're guaranteed that some transaction flags are set
2247 // so we can call handleTransactionLocked() unconditionally.
2248 // We call getTransactionFlags(), which will also clear the flags,
2249 // with mStateLock held to guarantee that mCurrentState won't change
2250 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002251
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002252 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002253 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002254 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002255
Mathias Agopianca4d3602011-05-19 15:38:14 -07002256 mLastTransactionTime = systemTime() - now;
2257 mDebugInTransaction = 0;
2258 invalidateHwcGeometry();
2259 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002260}
2261
Lloyd Pique715a2c12017-12-14 17:18:08 -08002262DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique09594832018-01-22 17:48:03 -08002263 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002264 // Figure out whether the event is for the primary display or an
2265 // external display by matching the Hwc display id against one for a
2266 // connected display. If we did not find a match, we then check what
2267 // displays are not already connected to determine the type. If we don't
2268 // have a connected primary display, we assume the new display is meant to
2269 // be the primary display, and then if we don't have an external display,
2270 // we assume it is that.
2271 const auto primaryDisplayId =
2272 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2273 const auto externalDisplayId =
2274 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2275 if (primaryDisplayId && primaryDisplayId == display) {
2276 return DisplayDevice::DISPLAY_PRIMARY;
2277 } else if (externalDisplayId && externalDisplayId == display) {
2278 return DisplayDevice::DISPLAY_EXTERNAL;
2279 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2280 return DisplayDevice::DISPLAY_PRIMARY;
2281 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2282 return DisplayDevice::DISPLAY_EXTERNAL;
2283 }
2284
2285 return DisplayDevice::DISPLAY_ID_INVALID;
2286}
2287
Lloyd Piqueba04e622017-12-14 17:11:26 -08002288void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2289 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002290 auto displayType = determineDisplayType(event.display, event.connection);
2291 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2292 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2293 continue;
2294 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002295
2296 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2297 ALOGE("External displays are not supported by the vr hardware composer.");
2298 continue;
2299 }
2300
Lloyd Pique715a2c12017-12-14 17:18:08 -08002301 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002302
2303 if (event.connection == HWC2::Connection::Connected) {
Steven Thomas3bed0522018-03-20 15:40:48 -07002304 if (!mBuiltinDisplays[displayType].get()) {
2305 ALOGV("Creating built in display %d", displayType);
2306 mBuiltinDisplays[displayType] = new BBinder();
2307 // All non-virtual displays are currently considered secure.
2308 DisplayDeviceState info(displayType, true);
2309 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2310 "Built-in Screen" : "External Screen";
2311 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
Lloyd Pique4d234852018-01-22 17:21:36 -08002312 mInterceptor->saveDisplayCreation(info);
Steven Thomas3bed0522018-03-20 15:40:48 -07002313 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002314 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002315 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002316
Lloyd Piquefcd86612017-12-14 17:15:36 -08002317 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2318 if (idx >= 0) {
2319 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Lloyd Pique4d234852018-01-22 17:21:36 -08002320 mInterceptor->saveDisplayDeletion(info.displayId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002321 mCurrentState.displays.removeItemsAt(idx);
2322 }
2323 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002324 }
2325
2326 processDisplayChangesLocked();
2327 }
2328
2329 mPendingHotplugEvents.clear();
2330}
2331
Lloyd Pique09594832018-01-22 17:48:03 -08002332sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2333 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2334 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002335 bool hasWideColorGamut = false;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002336 std::unordered_map<ColorMode, std::vector<RenderIntent>> hdrAndRenderIntents;
2337
Lloyd Pique09594832018-01-22 17:48:03 -08002338 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002339 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Lloyd Pique09594832018-01-22 17:48:03 -08002340 for (ColorMode colorMode : modes) {
2341 switch (colorMode) {
2342 case ColorMode::DISPLAY_P3:
2343 case ColorMode::ADOBE_RGB:
2344 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002345 hasWideColorGamut = true;
Lloyd Pique09594832018-01-22 17:48:03 -08002346 break;
2347 default:
2348 break;
2349 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002350
2351 std::vector<RenderIntent> renderIntents = getHwComposer().getRenderIntents(hwcId,
2352 colorMode);
2353 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2354 for (auto intent : renderIntents) {
2355 if (intent == RenderIntent::ENHANCE) {
2356 mBuiltinDisplaySupportsEnhance = true;
2357 break;
2358 }
2359 }
2360 }
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002361
2362 if (colorMode == ColorMode::BT2100_PQ || colorMode == ColorMode::BT2100_HLG) {
2363 hdrAndRenderIntents.emplace(colorMode, renderIntents);
2364 }
Lloyd Pique09594832018-01-22 17:48:03 -08002365 }
2366 }
2367
Peiyong Lin62665892018-04-16 11:07:44 -07002368 HdrCapabilities hdrCapabilities;
2369 getHwComposer().getHdrCapabilities(hwcId, &hdrCapabilities);
Lloyd Pique09594832018-01-22 17:48:03 -08002370
2371 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2372 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2373
2374 /*
2375 * Create our display's surface
2376 */
2377 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2378 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
2379 renderSurface->setAsync(state.type >= DisplayDevice::DISPLAY_VIRTUAL);
2380 renderSurface->setNativeWindow(nativeWindow.get());
2381 const int displayWidth = renderSurface->queryWidth();
2382 const int displayHeight = renderSurface->queryHeight();
2383
2384 // Make sure that composition can never be stalled by a virtual display
2385 // consumer that isn't processing buffers fast enough. We have to do this
2386 // in two places:
2387 // * Here, in case the display is composed entirely by HWC.
2388 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2389 // window's swap interval in eglMakeCurrent, so they'll override the
2390 // interval we set here.
2391 if (state.type >= DisplayDevice::DISPLAY_VIRTUAL) {
2392 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2393 }
2394
2395 // virtual displays are always considered enabled
2396 auto initialPowerMode = (state.type >= DisplayDevice::DISPLAY_VIRTUAL) ? HWC_POWER_MODE_NORMAL
2397 : HWC_POWER_MODE_OFF;
2398
2399 sp<DisplayDevice> hw =
2400 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2401 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
Peiyong Lin2c327ac2018-04-19 22:06:34 -07002402 hasWideColorGamut, hdrCapabilities,
2403 getHwComposer().getSupportedPerFrameMetadata(hwcId),
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002404 hdrAndRenderIntents, initialPowerMode);
Lloyd Pique09594832018-01-22 17:48:03 -08002405
2406 if (maxFrameBufferAcquiredBuffers >= 3) {
2407 nativeWindowSurface->preallocateBuffers();
2408 }
2409
2410 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002411 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2412 if (hasWideColorGamut) {
Lloyd Pique09594832018-01-22 17:48:03 -08002413 defaultColorMode = ColorMode::SRGB;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002414 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique09594832018-01-22 17:48:03 -08002415 }
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002416 setActiveColorModeInternal(hw, defaultColorMode, defaultDataSpace,
2417 RenderIntent::COLORIMETRIC);
Lloyd Pique09594832018-01-22 17:48:03 -08002418 hw->setLayerStack(state.layerStack);
2419 hw->setProjection(state.orientation, state.viewport, state.frame);
2420 hw->setDisplayName(state.displayName);
2421
2422 return hw;
2423}
2424
Lloyd Pique347200f2017-12-14 17:00:15 -08002425void SurfaceFlinger::processDisplayChangesLocked() {
2426 // here we take advantage of Vector's copy-on-write semantics to
2427 // improve performance by skipping the transaction entirely when
2428 // know that the lists are identical
2429 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2430 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2431 if (!curr.isIdenticalTo(draw)) {
2432 mVisibleRegionsDirty = true;
2433 const size_t cc = curr.size();
2434 size_t dc = draw.size();
2435
2436 // find the displays that were removed
2437 // (ie: in drawing state but not in current state)
2438 // also handle displays that changed
2439 // (ie: displays that are in both lists)
2440 for (size_t i = 0; i < dc;) {
2441 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2442 if (j < 0) {
2443 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002444 // Call makeCurrent() on the primary display so we can
2445 // be sure that nothing associated with this display
2446 // is current.
2447 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2448 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2449 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2450 if (hw != nullptr) hw->disconnect(getHwComposer());
2451 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2452 mEventThread->onHotplugReceived(draw[i].type, false);
2453 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002454 } else {
2455 // this display is in both lists. see if something changed.
2456 const DisplayDeviceState& state(curr[j]);
2457 const wp<IBinder>& display(curr.keyAt(j));
2458 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2459 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2460 if (state_binder != draw_binder) {
2461 // changing the surface is like destroying and
2462 // recreating the DisplayDevice, so we just remove it
2463 // from the drawing state, so that it get re-added
2464 // below.
2465 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2466 if (hw != nullptr) hw->disconnect(getHwComposer());
2467 mDisplays.removeItem(display);
2468 mDrawingState.displays.removeItemsAt(i);
2469 dc--;
2470 // at this point we must loop to the next item
2471 continue;
2472 }
2473
2474 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2475 if (disp != nullptr) {
2476 if (state.layerStack != draw[i].layerStack) {
2477 disp->setLayerStack(state.layerStack);
2478 }
2479 if ((state.orientation != draw[i].orientation) ||
2480 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2481 disp->setProjection(state.orientation, state.viewport, state.frame);
2482 }
2483 if (state.width != draw[i].width || state.height != draw[i].height) {
2484 disp->setDisplaySize(state.width, state.height);
2485 }
2486 }
2487 }
2488 ++i;
2489 }
2490
2491 // find displays that were added
2492 // (ie: in current state but not in drawing state)
2493 for (size_t i = 0; i < cc; i++) {
2494 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2495 const DisplayDeviceState& state(curr[i]);
2496
2497 sp<DisplaySurface> dispSurface;
2498 sp<IGraphicBufferProducer> producer;
2499 sp<IGraphicBufferProducer> bqProducer;
2500 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002501 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002502
2503 int32_t hwcId = -1;
2504 if (state.isVirtualDisplay()) {
2505 // Virtual displays without a surface are dormant:
2506 // they have external state (layer stack, projection,
2507 // etc.) but no internal state (i.e. a DisplayDevice).
2508 if (state.surface != nullptr) {
2509 // Allow VR composer to use virtual displays.
2510 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2511 int width = 0;
2512 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2513 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2514 int height = 0;
2515 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2516 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2517 int intFormat = 0;
2518 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2519 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002520 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002521
2522 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2523 }
2524
2525 // TODO: Plumb requested format back up to consumer
2526
2527 sp<VirtualDisplaySurface> vds =
2528 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2529 bqProducer, bqConsumer,
2530 state.displayName);
2531
2532 dispSurface = vds;
2533 producer = vds;
2534 }
2535 } else {
2536 ALOGE_IF(state.surface != nullptr,
2537 "adding a supported display, but rendering "
2538 "surface is provided (%p), ignoring it",
2539 state.surface.get());
2540
2541 hwcId = state.type;
2542 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2543 producer = bqProducer;
2544 }
2545
2546 const wp<IBinder>& display(curr.keyAt(i));
2547 if (dispSurface != nullptr) {
Lloyd Pique09594832018-01-22 17:48:03 -08002548 mDisplays.add(display,
2549 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2550 producer));
Lloyd Pique347200f2017-12-14 17:00:15 -08002551 if (!state.isVirtualDisplay()) {
2552 mEventThread->onHotplugReceived(state.type, true);
2553 }
2554 }
2555 }
2556 }
2557 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002558
2559 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002560}
2561
Mathias Agopian87baae12012-07-31 12:38:26 -07002562void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002563{
Dan Stoza7dde5992015-05-22 09:51:44 -07002564 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002565 mCurrentState.traverseInZOrder([](Layer* layer) {
2566 layer->notifyAvailableFrames();
2567 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002568
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002569 /*
2570 * Traversal of the children
2571 * (perform the transaction for each of them if needed)
2572 */
2573
Mathias Agopian3559b072012-08-15 13:46:03 -07002574 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002575 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002576 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002577 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002578
2579 const uint32_t flags = layer->doTransaction(0);
2580 if (flags & Layer::eVisibleRegion)
2581 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002582 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002583 }
2584
2585 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002586 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002587 */
2588
Mathias Agopiane57f2922012-08-09 16:29:12 -07002589 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002590 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002591 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002592 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002593
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002594 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002595 // The transform hint might have changed for some layers
2596 // (either because a display has changed, or because a layer
2597 // as changed).
2598 //
2599 // Walk through all the layers in currentLayers,
2600 // and update their transform hint.
2601 //
2602 // If a layer is visible only on a single display, then that
2603 // display is used to calculate the hint, otherwise we use the
2604 // default display.
2605 //
2606 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2607 // the hint is set before we acquire a buffer from the surface texture.
2608 //
2609 // NOTE: layer transactions have taken place already, so we use their
2610 // drawing state. However, SurfaceFlinger's own transaction has not
2611 // happened yet, so we must use the current state layer list
2612 // (soon to become the drawing state list).
2613 //
2614 sp<const DisplayDevice> disp;
2615 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002616 bool first = true;
2617 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002618 // NOTE: we rely on the fact that layers are sorted by
2619 // layerStack first (so we don't have to traverse the list
2620 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002621 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002622 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002623 currentlayerStack = layerStack;
2624 // figure out if this layerstack is mirrored
2625 // (more than one display) if so, pick the default display,
2626 // if not, pick the only display it's on.
2627 disp.clear();
2628 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2629 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002630 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002631 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002632 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002633 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002634 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002635 break;
2636 }
2637 }
2638 }
2639 }
Chet Haase91d25932013-04-11 15:24:55 -07002640
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002641 if (disp == nullptr) {
2642 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2643 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002644
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002645 // could be null when this layer is using a layerStack
2646 // that is not visible on any display. Also can occur at
2647 // screen off/on times.
2648 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002649 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002650
2651 // disp can be null if there is no display available at all to get
2652 // the transform hint from.
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002653 if (disp != nullptr) {
2654 layer->updateTransformHint(disp);
2655 }
Robert Carr2047fae2016-11-28 14:09:09 -08002656
2657 first = false;
2658 });
Mathias Agopian84300952012-11-21 16:02:13 -08002659 }
2660
2661
Mathias Agopian3559b072012-08-15 13:46:03 -07002662 /*
2663 * Perform our own transaction if needed
2664 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002665
2666 if (mLayersAdded) {
2667 mLayersAdded = false;
2668 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002669 mVisibleRegionsDirty = true;
2670 }
2671
2672 // some layers might have been removed, so
2673 // we need to update the regions they're exposing.
2674 if (mLayersRemoved) {
2675 mLayersRemoved = false;
2676 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002677 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002678 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002679 // this layer is not visible anymore
2680 // TODO: we could traverse the tree from front to back and
2681 // compute the actual visible region
2682 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002683 Region visibleReg;
2684 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002685 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002686 }
Robert Carr2047fae2016-11-28 14:09:09 -08002687 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002688 }
2689
2690 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002691
2692 updateCursorAsync();
2693}
2694
2695void SurfaceFlinger::updateCursorAsync()
2696{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002697 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2698 auto& displayDevice = mDisplays[displayId];
2699 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002700 continue;
2701 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002702
2703 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2704 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002705 }
2706 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002707}
2708
2709void SurfaceFlinger::commitTransaction()
2710{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002711 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002712 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002713 for (const auto& l : mLayersPendingRemoval) {
2714 recordBufferingStats(l->getName().string(),
2715 l->getOccupancyHistory(true));
2716 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002717 }
2718 mLayersPendingRemoval.clear();
2719 }
2720
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002721 // If this transaction is part of a window animation then the next frame
2722 // we composite should be considered an animation as well.
2723 mAnimCompositionPending = mAnimTransactionPending;
2724
Mathias Agopian4fec8732012-06-29 14:12:52 -07002725 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002726 // clear the "changed" flags in current state
2727 mCurrentState.colorMatrixChanged = false;
2728
Robert Carr1f0a16a2016-10-24 16:27:39 -07002729 mDrawingState.traverseInZOrder([](Layer* layer) {
2730 layer->commitChildList();
2731 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002732 mTransactionPending = false;
2733 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002734 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002735}
2736
Chia-I Wuab0c3192017-08-01 11:29:00 -07002737void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002738 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002739{
Mathias Agopian841cde52012-03-01 15:44:37 -08002740 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002741 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002742
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002743 Region aboveOpaqueLayers;
2744 Region aboveCoveredLayers;
2745 Region dirty;
2746
Mathias Agopian87baae12012-07-31 12:38:26 -07002747 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002748
Robert Carr2047fae2016-11-28 14:09:09 -08002749 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002750 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002751 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002752
Jesse Hall01e29052013-02-19 16:13:35 -08002753 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002754 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002755 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002756
Mathias Agopianab028732010-03-16 16:41:46 -07002757 /*
2758 * opaqueRegion: area of a surface that is fully opaque.
2759 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002760 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002761
2762 /*
2763 * visibleRegion: area of a surface that is visible on screen
2764 * and not fully transparent. This is essentially the layer's
2765 * footprint minus the opaque regions above it.
2766 * Areas covered by a translucent surface are considered visible.
2767 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002768 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002769
2770 /*
2771 * coveredRegion: area of a surface that is covered by all
2772 * visible regions above it (which includes the translucent areas).
2773 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002774 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002775
Jesse Halla8026d22012-09-25 13:25:04 -07002776 /*
2777 * transparentRegion: area of a surface that is hinted to be completely
2778 * transparent. This is only used to tell when the layer has no visible
2779 * non-transparent regions and can be removed from the layer list. It
2780 * does not affect the visibleRegion of this layer or any layers
2781 * beneath it. The hint may not be correct if apps don't respect the
2782 * SurfaceView restrictions (which, sadly, some don't).
2783 */
2784 Region transparentRegion;
2785
Mathias Agopianab028732010-03-16 16:41:46 -07002786
2787 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002788 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002789 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002790 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002791 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002792 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002793 if (!visibleRegion.isEmpty()) {
2794 // Remove the transparent area from the visible region
2795 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002796 if (tr.preserveRects()) {
2797 // transform the transparent region
2798 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002799 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002800 // transformation too complex, can't do the
2801 // transparent region optimization.
2802 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002803 }
Mathias Agopianab028732010-03-16 16:41:46 -07002804 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002805
Mathias Agopianab028732010-03-16 16:41:46 -07002806 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002807 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002808 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002809 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2810 // the opaque region is the layer's footprint
2811 opaqueRegion = visibleRegion;
2812 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002813 }
2814 }
2815
Robert Carre5f4f692018-01-12 13:12:28 -08002816 if (visibleRegion.isEmpty()) {
2817 layer->clearVisibilityRegions();
2818 return;
2819 }
2820
Mathias Agopianab028732010-03-16 16:41:46 -07002821 // Clip the covered region to the visible region
2822 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2823
2824 // Update aboveCoveredLayers for next (lower) layer
2825 aboveCoveredLayers.orSelf(visibleRegion);
2826
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002827 // subtract the opaque region covered by the layers above us
2828 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002829
2830 // compute this layer's dirty region
2831 if (layer->contentDirty) {
2832 // we need to invalidate the whole region
2833 dirty = visibleRegion;
2834 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002835 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002836 layer->contentDirty = false;
2837 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002838 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002839 * the exposed region consists of two components:
2840 * 1) what's VISIBLE now and was COVERED before
2841 * 2) what's EXPOSED now less what was EXPOSED before
2842 *
2843 * note that (1) is conservative, we start with the whole
2844 * visible region but only keep what used to be covered by
2845 * something -- which mean it may have been exposed.
2846 *
2847 * (2) handles areas that were not covered by anything but got
2848 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002849 */
Mathias Agopianab028732010-03-16 16:41:46 -07002850 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002851 const Region oldVisibleRegion = layer->visibleRegion;
2852 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002853 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2854 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002855 }
2856 dirty.subtractSelf(aboveOpaqueLayers);
2857
2858 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002859 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002860
Mathias Agopianab028732010-03-16 16:41:46 -07002861 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002862 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002863
Jesse Halla8026d22012-09-25 13:25:04 -07002864 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002865 layer->setVisibleRegion(visibleRegion);
2866 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002867 layer->setVisibleNonTransparentRegion(
2868 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002869 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002870
Mathias Agopian87baae12012-07-31 12:38:26 -07002871 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002872}
2873
Chia-I Wuab0c3192017-08-01 11:29:00 -07002874void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002875 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002876 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002877 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002878 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002879 }
2880 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002881}
2882
Dan Stoza6b9454d2014-11-07 16:00:59 -08002883bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002884{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002885 ALOGV("handlePageFlip");
2886
Brian Andersond6927fb2016-07-23 23:37:30 -07002887 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002888
Mathias Agopian4fec8732012-06-29 14:12:52 -07002889 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002890 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002891 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002892
2893 // Store the set of layers that need updates. This set must not change as
2894 // buffers are being latched, as this could result in a deadlock.
2895 // Example: Two producers share the same command stream and:
2896 // 1.) Layer 0 is latched
2897 // 2.) Layer 0 gets a new frame
2898 // 2.) Layer 1 gets a new frame
2899 // 3.) Layer 1 is latched.
2900 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2901 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002902 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002903 if (layer->hasQueuedFrame()) {
2904 frameQueued = true;
2905 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002906 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002907 } else {
2908 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002909 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002910 } else {
2911 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002912 }
Robert Carr2047fae2016-11-28 14:09:09 -08002913 });
2914
Dan Stoza9e56aa02015-11-02 13:00:03 -08002915 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002916 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002917 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002918 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002919 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002920 newDataLatched = true;
2921 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002922 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002923
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002924 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002925
2926 // If we will need to wake up at some time in the future to deal with a
2927 // queued frame that shouldn't be displayed during this vsync period, wake
2928 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002929 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002930 signalLayerUpdate();
2931 }
2932
2933 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002934 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002935}
2936
Mathias Agopianad456f92011-01-13 17:53:01 -08002937void SurfaceFlinger::invalidateHwcGeometry()
2938{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002939 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002940}
2941
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002942
Fabien Sanglard830b8472016-11-30 16:35:58 -08002943void SurfaceFlinger::doDisplayComposition(
2944 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002945 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002946{
Dan Stoza71433162014-02-04 16:22:36 -08002947 // We only need to actually compose the display if:
2948 // 1) It is being handled by hardware composer, which may need this to
2949 // keep its virtual display state machine in sync, or
2950 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002951 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002952 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002953 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002954 return;
2955 }
2956
Dan Stoza9e56aa02015-11-02 13:00:03 -08002957 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002958 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002959
2960 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002961 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002962}
2963
Chia-I Wub02087d2017-11-09 10:19:54 -08002964bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002965{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002966 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002967
Chia-I Wub02087d2017-11-09 10:19:54 -08002968 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002969 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002970 const auto hwcId = displayDevice->getHwcDisplayId();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002971 const bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002972 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002973
Chia-I Wu8e50e692018-05-04 10:12:37 -07002974 bool applyColorMatrix = false;
2975 bool applyLegacyColorMatrix = false;
2976 mat4 colorMatrix;
2977 mat4 legacyColorMatrix;
2978 const mat4* currentColorMatrix = nullptr;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002979
Dan Stoza9e56aa02015-11-02 13:00:03 -08002980 if (hasClientComposition) {
2981 ALOGV("hasClientComposition");
2982
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002983 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002984 if (displayDevice->hasWideColorGamut()) {
2985 outputDataspace = displayDevice->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002986 }
2987 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002988 getBE().mRenderEngine->setDisplayMaxLuminance(
2989 displayDevice->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002990
Chia-I Wu8e50e692018-05-04 10:12:37 -07002991 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
2992 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2993 HWC2::Capability::SkipClientColorTransform);
2994
2995 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2996 if (applyColorMatrix) {
2997 colorMatrix = mDrawingState.colorMatrix;
2998 }
2999
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07003000 applyLegacyColorMatrix = (mDisplayColorSetting == DisplayColorSetting::ENHANCED &&
3001 outputDataspace != Dataspace::UNKNOWN &&
3002 outputDataspace != Dataspace::SRGB);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003003 if (applyLegacyColorMatrix) {
3004 if (applyColorMatrix) {
3005 legacyColorMatrix = colorMatrix * mLegacySrgbSaturationMatrix;
3006 } else {
3007 legacyColorMatrix = mLegacySrgbSaturationMatrix;
3008 }
3009 }
3010
Chia-I Wu7f402902017-11-09 12:51:10 -08003011 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003012 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003013 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08003014 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003015
3016 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08003017 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07003018 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
3019 }
3020 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003021 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003022
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003023 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003024 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003025 // when using overlays, we assume a fully transparent framebuffer
3026 // NOTE: we could reduce how much we need to clear, for instance
3027 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003028 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003029 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003030 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003031 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003032 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003033 // we're left with the letterbox region
3034 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08003035 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07003036
3037 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08003038 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07003039
Mathias Agopianb9494d52012-04-18 02:28:45 -07003040 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003041 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003042 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08003043 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003044 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003045 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003046
Dan Stoza9e56aa02015-11-02 13:00:03 -08003047 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07003048 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07003049 // scissor on the main display. It should never be needed
3050 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08003051 const Rect& bounds(displayDevice->getBounds());
3052 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003053 if (scissor != bounds) {
3054 // scissor doesn't match the screen's dimensions, so we
3055 // need to clear everything outside of it and enable
3056 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003057
Mathias Agopianf45c5102012-10-24 16:29:17 -07003058 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08003059 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08003060 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07003061 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003062 }
3063 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003064 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003065
Mathias Agopian85d751c2012-08-29 16:59:24 -07003066 /*
3067 * and then, render the layers targeted at the framebuffer
3068 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003069
Dan Stoza9e56aa02015-11-02 13:00:03 -08003070 ALOGV("Rendering client layers");
3071 const Transform& displayTransform = displayDevice->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003072 bool firstLayer = true;
3073 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
3074 const Region clip(bounds.intersect(
3075 displayTransform.transform(layer->visibleRegion)));
3076 ALOGV("Layer: %s", layer->getName().string());
3077 ALOGV(" Composition type: %s",
3078 to_string(layer->getCompositionType(hwcId)).c_str());
3079 if (!clip.isEmpty()) {
3080 switch (layer->getCompositionType(hwcId)) {
3081 case HWC2::Composition::Cursor:
3082 case HWC2::Composition::Device:
3083 case HWC2::Composition::Sideband:
3084 case HWC2::Composition::SolidColor: {
3085 const Layer::State& state(layer->getDrawingState());
3086 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
3087 layer->isOpaque(state) && (state.color.a == 1.0f)
3088 && hasClientComposition) {
3089 // never clear the very first layer since we're
3090 // guaranteed the FB is already cleared
3091 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003092 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003093 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003094 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003095 case HWC2::Composition::Client: {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003096 // switch color matrices lazily
3097 if (layer->isLegacyDataSpace()) {
3098 if (applyLegacyColorMatrix && currentColorMatrix != &legacyColorMatrix) {
Peiyong Lind6fa4a72018-04-17 15:09:44 -07003099 // TODO(b/78891890) Legacy sRGB saturation matrix should be set
3100 // separately.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003101 getRenderEngine().setupColorTransform(legacyColorMatrix);
3102 currentColorMatrix = &legacyColorMatrix;
3103 }
3104 } else {
3105 if (applyColorMatrix && currentColorMatrix != &colorMatrix) {
3106 getRenderEngine().setupColorTransform(colorMatrix);
3107 currentColorMatrix = &colorMatrix;
3108 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003109 }
Chia-I Wu8e50e692018-05-04 10:12:37 -07003110
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003111 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003112 break;
3113 }
3114 default:
3115 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003116 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003117 } else {
3118 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003119 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003120 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003121 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003122
Chia-I Wu8e50e692018-05-04 10:12:37 -07003123 if (applyColorMatrix || applyLegacyColorMatrix) {
3124 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003125 }
3126
Mathias Agopianf45c5102012-10-24 16:29:17 -07003127 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003128 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003129 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003130}
3131
Fabien Sanglard830b8472016-11-30 16:35:58 -08003132void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
3133 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003134 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003135 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003136}
3137
Dan Stoza7d89d062015-04-30 13:29:25 -07003138status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003139 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003140 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003141 const sp<Layer>& lbc,
3142 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003143{
Dan Stoza7d89d062015-04-30 13:29:25 -07003144 // add this layer to the current state list
3145 {
3146 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003147 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003148 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3149 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003150 return NO_MEMORY;
3151 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003152 if (parent == nullptr) {
3153 mCurrentState.layersSortedByZ.add(lbc);
3154 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003155 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003156 ALOGE("addClientLayer called with a removed parent");
3157 return NAME_NOT_FOUND;
3158 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003159 parent->addChild(lbc);
3160 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003161
Dan Stoza101d8dc2018-02-27 15:42:25 -08003162 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
Dan Stoza0a0158c2018-03-16 13:38:54 -07003163 // TODO (b/74616334): Change this back to a fatal assert once the leak is fixed
3164 ALOGE_IF(mGraphicBufferProducerList.size() > mMaxGraphicBufferProducerListSize,
3165 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3166 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize,
3167 mNumLayers);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003168 mLayersAdded = true;
3169 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003170 }
3171
Mathias Agopian96f08192010-06-02 23:28:45 -07003172 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003173 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003174
Dan Stoza7d89d062015-04-30 13:29:25 -07003175 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003176}
3177
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003178status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003179 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003180 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3181}
Robert Carr7f9b8992017-03-10 11:08:39 -08003182
chaviwca27f252018-02-06 16:46:39 -08003183status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3184 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003185 if (layer->isPendingRemoval()) {
3186 return NO_ERROR;
3187 }
3188
Robert Carr1f0a16a2016-10-24 16:27:39 -07003189 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003190 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003191 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003192 if (topLevelOnly) {
3193 return NO_ERROR;
3194 }
3195
Chia-I Wu98f1c102017-05-30 14:54:08 -07003196 sp<Layer> ancestor = p;
3197 while (ancestor->getParent() != nullptr) {
3198 ancestor = ancestor->getParent();
3199 }
3200 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3201 ALOGE("removeLayer called with a layer whose parent has been removed");
3202 return NAME_NOT_FOUND;
3203 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003204
3205 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003206 } else {
3207 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003208 }
3209
Robert Carr136e2f62017-02-08 17:54:29 -08003210 // As a matter of normal operation, the LayerCleaner will produce a second
3211 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3212 // so we will succeed in promoting it, but it's already been removed
3213 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3214 // otherwise something has gone wrong and we are leaking the layer.
3215 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003216 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3217 layer->getName().string(),
3218 (p != nullptr) ? p->getName().string() : "no-parent");
3219 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003220 } else if (index < 0) {
3221 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003222 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003223
Chia-I Wuc6657022017-08-15 11:18:17 -07003224 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003225 mLayersPendingRemoval.add(layer);
3226 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003227 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003228 setTransactionFlags(eTransactionNeeded);
3229 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003230}
3231
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003232uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003233 return android_atomic_release_load(&mTransactionFlags);
3234}
3235
Mathias Agopian3f844832013-08-07 21:24:32 -07003236uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003237 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3238}
3239
Mathias Agopian3f844832013-08-07 21:24:32 -07003240uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza2713c302018-03-28 17:07:36 -07003241 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3242}
3243
3244uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3245 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003246 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza2713c302018-03-28 17:07:36 -07003247 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003248 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003249 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003250 }
3251 return old;
3252}
3253
chaviwca27f252018-02-06 16:46:39 -08003254bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3255 for (const ComposerState& state : states) {
3256 // Here we need to check that the interface we're given is indeed
3257 // one of our own. A malicious client could give us a nullptr
3258 // IInterface, or one of its own or even one of our own but a
3259 // different type. All these situations would cause us to crash.
3260 if (state.client == nullptr) {
3261 return true;
3262 }
3263
3264 sp<IBinder> binder = IInterface::asBinder(state.client);
3265 if (binder == nullptr) {
3266 return true;
3267 }
3268
3269 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3270 return true;
3271 }
3272 }
3273 return false;
3274}
3275
Mathias Agopian8b33f032012-07-24 20:43:54 -07003276void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003277 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003278 const Vector<DisplayState>& displays,
3279 uint32_t flags)
3280{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003281 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003282 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003283 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003284
chaviwca27f252018-02-06 16:46:39 -08003285 if (containsAnyInvalidClientState(states)) {
3286 return;
3287 }
3288
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003289 if (flags & eAnimation) {
3290 // For window updates that are part of an animation we must wait for
3291 // previous animation "frames" to be handled.
3292 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003293 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003294 if (CC_UNLIKELY(err != NO_ERROR)) {
3295 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003296 // caller after a few seconds.
3297 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3298 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003299 mAnimTransactionPending = false;
3300 break;
3301 }
3302 }
3303 }
3304
chaviwca27f252018-02-06 16:46:39 -08003305 for (const DisplayState& display : displays) {
3306 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003307 }
3308
chaviwca27f252018-02-06 16:46:39 -08003309 for (const ComposerState& state : states) {
3310 transactionFlags |= setClientStateLocked(state);
3311 }
3312
3313 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3314 // as destroyed should only occur after setting all other states. This is to allow for a
3315 // child re-parent to happen before marking its original parent as destroyed (which would
3316 // then mark the child as destroyed).
3317 for (const ComposerState& state : states) {
3318 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003319 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003320
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003321 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3322 // anyway. This can be used as a flush mechanism for previous async transactions.
3323 // Empty animation transaction can be used to simulate back-pressure, so also force a
3324 // transaction for empty animation transactions.
3325 if (transactionFlags == 0 &&
3326 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003327 transactionFlags = eTransactionNeeded;
3328 }
3329
Mathias Agopian386aa982011-11-07 21:58:03 -08003330 if (transactionFlags) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003331 if (mInterceptor->isEnabled()) {
3332 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003333 }
Irvel468051e2016-06-13 16:44:44 -07003334
Mathias Agopian386aa982011-11-07 21:58:03 -08003335 // this triggers the transaction
Dan Stoza2713c302018-03-28 17:07:36 -07003336 const auto start = (flags & eEarlyWakeup)
3337 ? VSyncModulator::TransactionStart::EARLY
3338 : VSyncModulator::TransactionStart::NORMAL;
3339 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003340
3341 // if this is a synchronous transaction, wait for it to take effect
3342 // before returning.
3343 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003344 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003345 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003346 if (flags & eAnimation) {
3347 mAnimTransactionPending = true;
3348 }
3349 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003350 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3351 if (CC_UNLIKELY(err != NO_ERROR)) {
3352 // just in case something goes wrong in SF, return to the
3353 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003354 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3355 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003356 break;
3357 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003358 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003359 }
3360}
3361
Mathias Agopiane57f2922012-08-09 16:29:12 -07003362uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3363{
Jesse Hall9a143922012-10-04 16:29:19 -07003364 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3365 if (dpyIdx < 0)
3366 return 0;
3367
Mathias Agopiane57f2922012-08-09 16:29:12 -07003368 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003369 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003370 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003371 const uint32_t what = s.what;
3372 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003373 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003374 disp.surface = s.surface;
3375 flags |= eDisplayTransactionNeeded;
3376 }
3377 }
3378 if (what & DisplayState::eLayerStackChanged) {
3379 if (disp.layerStack != s.layerStack) {
3380 disp.layerStack = s.layerStack;
3381 flags |= eDisplayTransactionNeeded;
3382 }
3383 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003384 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003385 if (disp.orientation != s.orientation) {
3386 disp.orientation = s.orientation;
3387 flags |= eDisplayTransactionNeeded;
3388 }
3389 if (disp.frame != s.frame) {
3390 disp.frame = s.frame;
3391 flags |= eDisplayTransactionNeeded;
3392 }
3393 if (disp.viewport != s.viewport) {
3394 disp.viewport = s.viewport;
3395 flags |= eDisplayTransactionNeeded;
3396 }
3397 }
Michael Lentine47e45402014-07-18 15:34:25 -07003398 if (what & DisplayState::eDisplaySizeChanged) {
3399 if (disp.width != s.width) {
3400 disp.width = s.width;
3401 flags |= eDisplayTransactionNeeded;
3402 }
3403 if (disp.height != s.height) {
3404 disp.height = s.height;
3405 flags |= eDisplayTransactionNeeded;
3406 }
3407 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003408 }
3409 return flags;
3410}
3411
chaviwca27f252018-02-06 16:46:39 -08003412uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3413 const layer_state_t& s = composerState.state;
3414 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3415
Mathias Agopian13127d82013-03-05 17:47:11 -08003416 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003417 if (layer == nullptr) {
3418 return 0;
3419 }
3420
3421 if (layer->isPendingRemoval()) {
3422 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3423 return 0;
3424 }
3425
3426 uint32_t flags = 0;
3427
3428 const uint32_t what = s.what;
3429 bool geometryAppliesWithResize =
3430 what & layer_state_t::eGeometryAppliesWithResize;
3431 if (what & layer_state_t::ePositionChanged) {
3432 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3433 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003434 }
chaviw8b3871a2017-11-01 17:41:01 -07003435 }
3436 if (what & layer_state_t::eLayerChanged) {
3437 // NOTE: index needs to be calculated before we update the state
3438 const auto& p = layer->getParent();
3439 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003440 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003441 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003442 mCurrentState.layersSortedByZ.removeAt(idx);
3443 mCurrentState.layersSortedByZ.add(layer);
3444 // we need traversal (state changed)
3445 // AND transaction (list changed)
3446 flags |= eTransactionNeeded|eTraversalNeeded;
3447 }
chaviw8b3871a2017-11-01 17:41:01 -07003448 } else {
3449 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003450 flags |= eTransactionNeeded|eTraversalNeeded;
3451 }
3452 }
chaviw8b3871a2017-11-01 17:41:01 -07003453 }
3454 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003455 // NOTE: index needs to be calculated before we update the state
3456 const auto& p = layer->getParent();
3457 if (p == nullptr) {
3458 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3459 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3460 mCurrentState.layersSortedByZ.removeAt(idx);
3461 mCurrentState.layersSortedByZ.add(layer);
3462 // we need traversal (state changed)
3463 // AND transaction (list changed)
3464 flags |= eTransactionNeeded|eTraversalNeeded;
3465 }
3466 } else {
3467 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3468 flags |= eTransactionNeeded|eTraversalNeeded;
3469 }
chaviw8b3871a2017-11-01 17:41:01 -07003470 }
3471 }
3472 if (what & layer_state_t::eSizeChanged) {
3473 if (layer->setSize(s.w, s.h)) {
3474 flags |= eTraversalNeeded;
3475 }
3476 }
3477 if (what & layer_state_t::eAlphaChanged) {
3478 if (layer->setAlpha(s.alpha))
3479 flags |= eTraversalNeeded;
3480 }
3481 if (what & layer_state_t::eColorChanged) {
3482 if (layer->setColor(s.color))
3483 flags |= eTraversalNeeded;
3484 }
3485 if (what & layer_state_t::eMatrixChanged) {
3486 if (layer->setMatrix(s.matrix))
3487 flags |= eTraversalNeeded;
3488 }
3489 if (what & layer_state_t::eTransparentRegionChanged) {
3490 if (layer->setTransparentRegionHint(s.transparentRegion))
3491 flags |= eTraversalNeeded;
3492 }
3493 if (what & layer_state_t::eFlagsChanged) {
3494 if (layer->setFlags(s.flags, s.mask))
3495 flags |= eTraversalNeeded;
3496 }
3497 if (what & layer_state_t::eCropChanged) {
3498 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3499 flags |= eTraversalNeeded;
3500 }
3501 if (what & layer_state_t::eFinalCropChanged) {
3502 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3503 flags |= eTraversalNeeded;
3504 }
3505 if (what & layer_state_t::eLayerStackChanged) {
3506 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3507 // We only allow setting layer stacks for top level layers,
3508 // everything else inherits layer stack from its parent.
3509 if (layer->hasParent()) {
3510 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3511 layer->getName().string());
3512 } else if (idx < 0) {
3513 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3514 "that also does not appear in the top level layer list. Something"
3515 " has gone wrong.", layer->getName().string());
3516 } else if (layer->setLayerStack(s.layerStack)) {
3517 mCurrentState.layersSortedByZ.removeAt(idx);
3518 mCurrentState.layersSortedByZ.add(layer);
3519 // we need traversal (state changed)
3520 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003521 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003522 }
3523 }
3524 if (what & layer_state_t::eDeferTransaction) {
3525 if (s.barrierHandle != nullptr) {
3526 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3527 } else if (s.barrierGbp != nullptr) {
3528 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3529 if (authenticateSurfaceTextureLocked(gbp)) {
3530 const auto& otherLayer =
3531 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3532 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3533 } else {
3534 ALOGE("Attempt to defer transaction to to an"
3535 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003536 }
3537 }
chaviw8b3871a2017-11-01 17:41:01 -07003538 // We don't trigger a traversal here because if no other state is
3539 // changed, we don't want this to cause any more work
3540 }
3541 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003542 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003543 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003544 if (!hadParent) {
3545 mCurrentState.layersSortedByZ.remove(layer);
3546 }
chaviw8b3871a2017-11-01 17:41:01 -07003547 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003548 }
chaviw8b3871a2017-11-01 17:41:01 -07003549 }
3550 if (what & layer_state_t::eReparentChildren) {
3551 if (layer->reparentChildren(s.reparentHandle)) {
3552 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003553 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003554 }
chaviw8b3871a2017-11-01 17:41:01 -07003555 if (what & layer_state_t::eDetachChildren) {
3556 layer->detachChildren();
3557 }
3558 if (what & layer_state_t::eOverrideScalingModeChanged) {
3559 layer->setOverrideScalingMode(s.overrideScalingMode);
3560 // We don't trigger a traversal here because if no other state is
3561 // changed, we don't want this to cause any more work
3562 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003563 return flags;
3564}
3565
chaviwca27f252018-02-06 16:46:39 -08003566void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3567 const layer_state_t& state = composerState.state;
3568 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3569
3570 sp<Layer> layer(client->getLayerUser(state.surface));
3571 if (layer == nullptr) {
3572 return;
3573 }
3574
3575 if (layer->isPendingRemoval()) {
3576 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3577 return;
3578 }
3579
3580 if (state.what & layer_state_t::eDestroySurface) {
3581 removeLayerLocked(mStateLock, layer);
3582 }
3583}
3584
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003585status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003586 const String8& name,
3587 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003588 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliuccd34842018-03-14 12:26:23 -07003589 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003590 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003591{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003592 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003593 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003594 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003595 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003596 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003597
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003598 status_t result = NO_ERROR;
3599
3600 sp<Layer> layer;
3601
Cody Northropbc755282017-03-31 12:00:08 -06003602 String8 uniqueName = getUniqueLayerName(name);
3603
Mathias Agopian3165cc22012-08-08 19:42:09 -07003604 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3605 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003606 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003607 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003608 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003609
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003610 break;
chaviw13fdc492017-06-27 12:40:18 -07003611 case ISurfaceComposerClient::eFXSurfaceColor:
3612 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003613 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003614 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003615 break;
3616 default:
3617 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003618 break;
3619 }
3620
Dan Stoza7d89d062015-04-30 13:29:25 -07003621 if (result != NO_ERROR) {
3622 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003623 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003624
Chia-I Wuab0c3192017-08-01 11:29:00 -07003625 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3626 // TODO b/64227542
3627 if (windowType == 441731) {
3628 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3629 layer->setPrimaryDisplayOnly();
3630 }
3631
Albert Chaulk479c60c2017-01-27 14:21:34 -05003632 layer->setInfo(windowType, ownerUid);
3633
Robert Carr1f0a16a2016-10-24 16:27:39 -07003634 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003635 if (result != NO_ERROR) {
3636 return result;
3637 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003638 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003639
3640 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003641 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003642}
3643
Cody Northropbc755282017-03-31 12:00:08 -06003644String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3645{
3646 bool matchFound = true;
3647 uint32_t dupeCounter = 0;
3648
3649 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3650 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3651
3652 // Loop over layers until we're sure there is no matching name
3653 while (matchFound) {
3654 matchFound = false;
3655 mDrawingState.traverseInZOrder([&](Layer* layer) {
3656 if (layer->getName() == uniqueName) {
3657 matchFound = true;
3658 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3659 }
3660 });
3661 }
3662
3663 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3664
3665 return uniqueName;
3666}
3667
David Sodman0c69cad2017-08-21 12:12:51 -07003668status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003669 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3670 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003671{
3672 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003673 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003674 case PIXEL_FORMAT_TRANSPARENT:
3675 case PIXEL_FORMAT_TRANSLUCENT:
3676 format = PIXEL_FORMAT_RGBA_8888;
3677 break;
3678 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003679 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003680 break;
3681 }
3682
David Sodman0c69cad2017-08-21 12:12:51 -07003683 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3684 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003685 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003686 *handle = layer->getHandle();
3687 *gbp = layer->getProducer();
3688 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003689 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003690
David Sodman0c69cad2017-08-21 12:12:51 -07003691 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003692 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003693}
3694
chaviw13fdc492017-06-27 12:40:18 -07003695status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003696 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003697 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003698{
chaviw13fdc492017-06-27 12:40:18 -07003699 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003700 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003701 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003702}
3703
Mathias Agopianac9fa422013-02-11 16:40:36 -08003704status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003705{
Robert Carr9524cb32017-02-13 11:32:32 -08003706 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003707 status_t err = NO_ERROR;
3708 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003709 if (l != nullptr) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003710 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003711 err = removeLayer(l);
3712 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3713 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003714 }
3715 return err;
3716}
3717
Mathias Agopian13127d82013-03-05 17:47:11 -08003718status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003719{
Mathias Agopian67106042013-03-14 19:18:13 -07003720 // called by ~LayerCleaner() when all references to the IBinder (handle)
3721 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003722 sp<Layer> l = layer.promote();
3723 if (l == nullptr) {
3724 // The layer has already been removed, carry on
3725 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003726 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003727 // If we have a parent, then we can continue to live as long as it does.
3728 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003729}
3730
Mathias Agopianb60314a2012-04-10 22:09:54 -07003731// ---------------------------------------------------------------------------
3732
Andy McFadden13a082e2012-08-24 10:16:42 -07003733void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003734 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003735 Vector<ComposerState> state;
3736 Vector<DisplayState> displays;
3737 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003738 d.what = DisplayState::eDisplayProjectionChanged |
3739 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003740 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003741 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003742 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003743 d.frame.makeInvalid();
3744 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003745 d.width = 0;
3746 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003747 displays.add(d);
3748 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003749 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3750 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003751
David Sodman105b7dc2017-11-04 20:28:14 -07003752 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003753 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003754 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003755
Brian Andersond0010582017-03-07 13:20:31 -08003756 // Use phase of 0 since phase is not known.
3757 // Use latency of 0, which will snap to the ideal latency.
3758 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003759}
3760
3761void SurfaceFlinger::initializeDisplays() {
3762 class MessageScreenInitialized : public MessageBase {
3763 SurfaceFlinger* flinger;
3764 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003765 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003766 virtual bool handler() {
3767 flinger->onInitializeDisplays();
3768 return true;
3769 }
3770 };
3771 sp<MessageBase> msg = new MessageScreenInitialized(this);
3772 postMessageAsync(msg); // we may be called from main thread, use async message
3773}
3774
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003775void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003776 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003777 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3778 this);
3779 int32_t type = hw->getDisplayType();
3780 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003781
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003782 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003783 return;
3784 }
3785
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003786 hw->setPowerMode(mode);
3787 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3788 ALOGW("Trying to set power mode for virtual display");
3789 return;
3790 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003791
Lloyd Pique4d234852018-01-22 17:21:36 -08003792 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003793 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003794 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3795 if (idx < 0) {
3796 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3797 return;
3798 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003799 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003800 }
3801
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003802 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003803 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003804 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003805 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3806 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003807 // FIXME: eventthread only knows about the main display right now
3808 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003809 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003810 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003811
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003812 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003813 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003814 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003815
3816 struct sched_param param = {0};
3817 param.sched_priority = 1;
3818 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3819 ALOGW("Couldn't set SCHED_FIFO on display on");
3820 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003821 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003822 // Turn off the display
3823 struct sched_param param = {0};
3824 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3825 ALOGW("Couldn't set SCHED_OTHER on display off");
3826 }
3827
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003828 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3829 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003830 disableHardwareVsync(true); // also cancels any in-progress resync
3831
Mathias Agopiancde87a32012-09-13 14:09:01 -07003832 // FIXME: eventthread only knows about the main display right now
3833 mEventThread->onScreenReleased();
3834 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003835
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003836 getHwComposer().setPowerMode(type, mode);
3837 mVisibleRegionsDirty = true;
3838 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003839 } else if (mode == HWC_POWER_MODE_DOZE ||
3840 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003841 // Update display while dozing
3842 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003843 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3844 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003845 // FIXME: eventthread only knows about the main display right now
3846 mEventThread->onScreenAcquired();
3847 resyncToHardwareVsync(true);
3848 }
3849 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3850 // Leave display going to doze
3851 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3852 disableHardwareVsync(true); // also cancels any in-progress resync
3853 // FIXME: eventthread only knows about the main display right now
3854 mEventThread->onScreenReleased();
3855 }
3856 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003857 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003858 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003859 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003860 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003861 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003862}
3863
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003864void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3865 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003866 SurfaceFlinger& mFlinger;
3867 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003868 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003869 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003870 MessageSetPowerMode(SurfaceFlinger& flinger,
3871 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3872 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003873 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003874 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003875 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003876 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003877 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003878 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003879 ALOGW("Attempt to set power mode = %d for virtual display",
3880 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003881 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003882 mFlinger.setPowerModeInternal(
3883 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003884 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003885 return true;
3886 }
3887 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003888 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003889 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003890}
3891
3892// ---------------------------------------------------------------------------
3893
Lloyd Pique755e3192018-01-31 16:46:15 -08003894status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3895 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003896 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003897
Mathias Agopianbd115332013-04-18 16:41:04 -07003898 IPCThreadState* ipc = IPCThreadState::self();
3899 const int pid = ipc->getCallingPid();
3900 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003901
Mathias Agopianbd115332013-04-18 16:41:04 -07003902 if ((uid != AID_SHELL) &&
3903 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003904 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003905 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003906 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003907 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003908 // (this would indicate SF is stuck, but we want to be able to
3909 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003910 status_t err = mStateLock.timedLock(s2ns(1));
3911 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003912 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003913 result.appendFormat(
3914 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3915 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003916 }
3917
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003918 bool dumpAll = true;
3919 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003920 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003921
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003922 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003923 if ((index < numArgs) &&
3924 (args[index] == String16("--list"))) {
3925 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003926 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003927 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003928 }
3929
3930 if ((index < numArgs) &&
3931 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003932 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003933 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003934 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003935 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003936
3937 if ((index < numArgs) &&
3938 (args[index] == String16("--latency-clear"))) {
3939 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003940 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003941 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003942 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003943
3944 if ((index < numArgs) &&
3945 (args[index] == String16("--dispsync"))) {
3946 index++;
3947 mPrimaryDispSync.dump(result);
3948 dumpAll = false;
3949 }
Dan Stozab90cf072015-03-05 11:05:59 -08003950
3951 if ((index < numArgs) &&
3952 (args[index] == String16("--static-screen"))) {
3953 index++;
3954 dumpStaticScreenStats(result);
3955 dumpAll = false;
3956 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003957
3958 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003959 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003960 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003961 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003962 dumpAll = false;
3963 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003964
3965 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3966 index++;
3967 dumpWideColorInfo(result);
3968 dumpAll = false;
3969 }
Yiwei Zhang068e31b2018-02-21 13:02:45 -08003970
3971 if ((index < numArgs) &&
3972 (args[index] == String16("--enable-layer-stats"))) {
3973 index++;
3974 mLayerStats.enable();
3975 dumpAll = false;
3976 }
3977
3978 if ((index < numArgs) &&
3979 (args[index] == String16("--disable-layer-stats"))) {
3980 index++;
3981 mLayerStats.disable();
3982 dumpAll = false;
3983 }
3984
3985 if ((index < numArgs) &&
3986 (args[index] == String16("--clear-layer-stats"))) {
3987 index++;
3988 mLayerStats.clear();
3989 dumpAll = false;
3990 }
3991
3992 if ((index < numArgs) &&
3993 (args[index] == String16("--dump-layer-stats"))) {
3994 index++;
3995 mLayerStats.dump(result);
3996 dumpAll = false;
3997 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -07003998
3999 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4000 index++;
4001 mTimeStats.parseArgs(asProto, args, index, result);
4002 dumpAll = false;
4003 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004004 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004005
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004006 if (dumpAll) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -07004007 if (asProto) {
4008 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4009 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4010 } else {
4011 dumpAllLocked(args, index, result);
4012 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004013 }
4014
Mathias Agopian9795c422009-08-26 16:36:26 -07004015 if (locked) {
4016 mStateLock.unlock();
4017 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004018 }
4019 write(fd, result.string(), result.size());
4020 return NO_ERROR;
4021}
4022
Dan Stozac7014012014-02-14 15:03:43 -08004023void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4024 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004025{
Robert Carr2047fae2016-11-28 14:09:09 -08004026 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004027 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004028 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004029}
4030
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004031void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004032 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004033{
4034 String8 name;
4035 if (index < args.size()) {
4036 name = String8(args[index]);
4037 index++;
4038 }
4039
David Sodman105b7dc2017-11-04 20:28:14 -07004040 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004041 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08004042 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004043
4044 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004045 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004046 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004047 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004048 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004049 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004050 }
Robert Carr2047fae2016-11-28 14:09:09 -08004051 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004052 }
4053}
4054
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004055void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004056 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004057{
4058 String8 name;
4059 if (index < args.size()) {
4060 name = String8(args[index]);
4061 index++;
4062 }
4063
Robert Carr2047fae2016-11-28 14:09:09 -08004064 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004065 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004066 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004067 }
Robert Carr2047fae2016-11-28 14:09:09 -08004068 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004069
Svetoslavd85084b2014-03-20 10:28:31 -07004070 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004071}
4072
Jamie Gennis6547ff42013-07-16 20:12:42 -07004073// This should only be called from the main thread. Otherwise it would need
4074// the lock and should use mCurrentState rather than mDrawingState.
4075void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004076 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004077 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004078 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004079
4080 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4081}
4082
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004083void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004084{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004085 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004086
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004087 if (isLayerTripleBufferingDisabled())
4088 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004089
4090 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004091 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004092 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004093 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004094 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4095 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004096 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004097}
4098
Dan Stozab90cf072015-03-05 11:05:59 -08004099void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4100{
4101 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004102 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4103 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004104 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004105 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004106 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4107 b + 1, bucketTimeSec, percent);
4108 }
David Sodman4a36e932017-11-07 14:29:47 -08004109 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004110 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004111 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004112 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004113 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004114}
4115
Dan Stozae77c7662016-05-13 11:37:28 -07004116void SurfaceFlinger::recordBufferingStats(const char* layerName,
4117 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004118 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4119 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004120 for (const auto& segment : history) {
4121 if (!segment.usedThirdBuffer) {
4122 stats.twoBufferTime += segment.totalTime;
4123 }
4124 if (segment.occupancyAverage < 1.0f) {
4125 stats.doubleBufferedTime += segment.totalTime;
4126 } else if (segment.occupancyAverage < 2.0f) {
4127 stats.tripleBufferedTime += segment.totalTime;
4128 }
4129 ++stats.numSegments;
4130 stats.totalTime += segment.totalTime;
4131 }
4132}
4133
Brian Andersond6927fb2016-07-23 23:37:30 -07004134void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4135 result.appendFormat("Layer frame timestamps:\n");
4136
4137 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4138 const size_t count = currentLayers.size();
4139 for (size_t i=0 ; i<count ; i++) {
4140 currentLayers[i]->dumpFrameEvents(result);
4141 }
4142}
4143
Dan Stozae77c7662016-05-13 11:37:28 -07004144void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4145 result.append("Buffering stats:\n");
4146 result.append(" [Layer name] <Active time> <Two buffer> "
4147 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004148 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004149 typedef std::tuple<std::string, float, float, float> BufferTuple;
4150 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004151 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004152 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004153 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004154 if (stats.numSegments == 0) {
4155 continue;
4156 }
4157 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4158 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4159 stats.totalTime;
4160 float doubleBufferRatio = static_cast<float>(
4161 stats.doubleBufferedTime) / stats.totalTime;
4162 float tripleBufferRatio = static_cast<float>(
4163 stats.tripleBufferedTime) / stats.totalTime;
4164 sorted.insert({activeTime, {name, twoBufferRatio,
4165 doubleBufferRatio, tripleBufferRatio}});
4166 }
4167 for (const auto& sortedPair : sorted) {
4168 float activeTime = sortedPair.first;
4169 const BufferTuple& values = sortedPair.second;
4170 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4171 std::get<0>(values).c_str(), activeTime,
4172 std::get<1>(values), std::get<2>(values),
4173 std::get<3>(values));
4174 }
4175 result.append("\n");
4176}
4177
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004178void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4179 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004180 result.appendFormat("DisplayColorSetting: %d\n", mDisplayColorSetting);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004181
4182 // TODO: print out if wide-color mode is active or not
4183
4184 for (size_t d = 0; d < mDisplays.size(); d++) {
4185 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4186 int32_t hwcId = displayDevice->getHwcDisplayId();
4187 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4188 continue;
4189 }
4190
4191 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004192 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004193 for (auto&& mode : modes) {
4194 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4195 }
4196
Peiyong Lina52f0292018-03-14 17:26:31 -07004197 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004198 result.appendFormat(" Current color mode: %s (%d)\n",
4199 decodeColorMode(currentMode).c_str(), currentMode);
4200 }
4201 result.append("\n");
4202}
4203
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004204LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004205 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004206 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4207 const State& state = useDrawing ? mDrawingState : mCurrentState;
4208 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004209 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004210 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004211 });
4212
4213 return layersProto;
4214}
4215
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004216LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4217 LayersProto layersProto;
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004218 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004219
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004220 SizeProto* resolution = layersProto.mutable_resolution();
4221 resolution->set_w(displayDevice->getWidth());
4222 resolution->set_h(displayDevice->getHeight());
4223
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004224 layersProto.set_color_mode(decodeColorMode(displayDevice->getActiveColorMode()));
4225 layersProto.set_color_transform(decodeColorTransform(displayDevice->getColorTransform()));
4226 layersProto.set_global_transform(
4227 static_cast<int32_t>(displayDevice->getOrientationTransform()));
4228
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004229 mDrawingState.traverseInZOrder([&](Layer* layer) {
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004230 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004231 LayerProto* layerProto = layersProto.add_layers();
4232 layer->writeToProto(layerProto, hwcId);
4233 }
4234 });
4235
4236 return layersProto;
4237}
4238
Mathias Agopian74d211a2013-04-22 16:55:35 +02004239void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4240 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004241{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004242 bool colorize = false;
4243 if (index < args.size()
4244 && (args[index] == String16("--color"))) {
4245 colorize = true;
4246 index++;
4247 }
4248
4249 Colorizer colorizer(colorize);
4250
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004251 // figure out if we're stuck somewhere
4252 const nsecs_t now = systemTime();
4253 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4254 const nsecs_t inTransaction(mDebugInTransaction);
4255 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4256 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4257
4258 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004259 * Dump library configuration.
4260 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004261
4262 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004263 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004264 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004265 appendSfConfigString(result);
4266 appendUiConfigString(result);
4267 appendGuiConfigString(result);
4268 result.append("\n");
4269
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004270 result.append("\nWide-Color information:\n");
4271 dumpWideColorInfo(result);
4272
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004273 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004274 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004275 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004276 result.append(SyncFeatures::getInstance().toString());
4277 result.append("\n");
4278
David Sodman105b7dc2017-11-04 20:28:14 -07004279 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004280
Andy McFadden41d67d72014-04-25 16:58:34 -07004281 colorizer.bold(result);
4282 result.append("DispSync configuration: ");
4283 colorizer.reset(result);
Dan Stoza2713c302018-03-28 17:07:36 -07004284 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, early sf phase %" PRId64
4285 " ns, present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4286 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, mVsyncModulator.getEarlyPhaseOffset(),
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004287 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004288 result.append("\n");
4289
Dan Stozab90cf072015-03-05 11:05:59 -08004290 // Dump static screen stats
4291 result.append("\n");
4292 dumpStaticScreenStats(result);
4293 result.append("\n");
4294
Dan Stozae77c7662016-05-13 11:37:28 -07004295 dumpBufferingStats(result);
4296
Andy McFadden4803b742012-09-24 19:07:20 -07004297 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004298 * Dump the visible layer list
4299 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004300 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004301 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004302 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4303 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004304 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004305
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004306 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004307 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7794ec12018-03-14 13:28:39 -07004308 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004309 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004310
4311 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004312 * Dump Display state
4313 */
4314
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004315 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004316 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004317 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004318 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4319 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004320 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004321 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004322 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004323
4324 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004325 * Dump SurfaceFlinger global state
4326 */
4327
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004328 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004329 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004330 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004331
Mathias Agopian888c8222012-08-04 21:10:38 -07004332 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004333 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004334
David Sodmanbc815282017-11-05 18:57:52 -08004335 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004336
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004337 if (hw) {
4338 hw->undefinedRegion.dump(result, "undefinedRegion");
4339 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4340 hw->getOrientation(), hw->isDisplayOn());
4341 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004342 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004343 " last eglSwapBuffers() time: %f us\n"
4344 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004345 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004346 " refresh-rate : %f fps\n"
4347 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004348 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004349 " gpu_to_cpu_unsupported : %d\n"
4350 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004351 mLastSwapBufferTime/1000.0,
4352 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004353 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004354 1e9 / activeConfig->getVsyncPeriod(),
4355 activeConfig->getDpiX(),
4356 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004357 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004358
Mathias Agopian74d211a2013-04-22 16:55:35 +02004359 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004360 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004361
Mathias Agopian74d211a2013-04-22 16:55:35 +02004362 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004363 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004364
4365 /*
4366 * VSYNC state
4367 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004368 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004369 result.append("\n");
4370
4371 /*
4372 * HWC layer minidump
4373 */
4374 for (size_t d = 0; d < mDisplays.size(); d++) {
4375 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4376 int32_t hwcId = displayDevice->getHwcDisplayId();
4377 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4378 continue;
4379 }
4380
4381 result.appendFormat("Display %d HWC layers:\n", hwcId);
4382 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004383 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004384 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004385 });
Dan Stozae22aec72016-08-01 13:20:59 -07004386 result.append("\n");
4387 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004388
4389 /*
4390 * Dump HWComposer state
4391 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004392 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004393 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004394 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004395 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004396 result.appendFormat(" h/w composer %s\n",
4397 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004398 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004399
4400 /*
4401 * Dump gralloc state
4402 */
4403 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4404 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004405
4406 /*
4407 * Dump VrFlinger state if in use.
4408 */
4409 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4410 result.append("VrFlinger state:\n");
4411 result.append(mVrFlinger->Dump().c_str());
4412 result.append("\n");
4413 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004414}
4415
Mathias Agopian13127d82013-03-05 17:47:11 -08004416const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004417SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004418 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004419 wp<IBinder> dpy;
4420 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4421 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4422 dpy = mDisplays.keyAt(i);
4423 break;
4424 }
4425 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004426 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004427 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4428 // Just use the primary display so we have something to return
4429 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4430 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004431 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004432}
4433
Keun young Park63f165f2012-08-31 10:53:36 -07004434bool SurfaceFlinger::startDdmConnection()
4435{
4436 void* libddmconnection_dso =
4437 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4438 if (!libddmconnection_dso) {
4439 return false;
4440 }
4441 void (*DdmConnection_start)(const char* name);
4442 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004443 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004444 if (!DdmConnection_start) {
4445 dlclose(libddmconnection_dso);
4446 return false;
4447 }
4448 (*DdmConnection_start)(getServiceName());
4449 return true;
4450}
4451
Chia-I Wu28f320b2018-05-03 11:02:56 -07004452void SurfaceFlinger::updateColorMatrixLocked() {
4453 mat4 colorMatrix;
4454 if (mGlobalSaturationFactor != 1.0f) {
4455 // Rec.709 luma coefficients
4456 float3 luminance{0.213f, 0.715f, 0.072f};
4457 luminance *= 1.0f - mGlobalSaturationFactor;
4458 mat4 saturationMatrix = mat4(
4459 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4460 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4461 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4462 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4463 );
4464 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4465 } else {
4466 colorMatrix = mClientColorMatrix * mDaltonizer();
4467 }
4468
4469 if (mCurrentState.colorMatrix != colorMatrix) {
4470 mCurrentState.colorMatrix = colorMatrix;
4471 mCurrentState.colorMatrixChanged = true;
4472 setTransactionFlags(eTransactionNeeded);
4473 }
4474}
4475
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004476status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004477 switch (code) {
4478 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004479 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004480 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004481 case CLEAR_ANIMATION_FRAME_STATS:
4482 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004483 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004484 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004485 case ENABLE_VSYNC_INJECTIONS:
4486 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004487 {
4488 // codes that require permission check
4489 IPCThreadState* ipc = IPCThreadState::self();
4490 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004491 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004492 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004493 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004494 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004495 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004496 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004497 break;
4498 }
Robert Carr1db73f62016-12-21 12:58:51 -08004499 /*
4500 * Calling setTransactionState is safe, because you need to have been
4501 * granted a reference to Client* and Handle* to do anything with it.
4502 *
4503 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4504 */
4505 case SET_TRANSACTION_STATE:
4506 case CREATE_SCOPED_CONNECTION:
4507 {
4508 return OK;
4509 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004510 case CAPTURE_SCREEN:
4511 {
4512 // codes that require permission check
4513 IPCThreadState* ipc = IPCThreadState::self();
4514 const int pid = ipc->getCallingPid();
4515 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004516 if ((uid != AID_GRAPHICS) &&
4517 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004518 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004519 return PERMISSION_DENIED;
4520 }
4521 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004522 }
chaviwa76b2712017-09-20 12:02:26 -07004523 case CAPTURE_LAYERS: {
4524 IPCThreadState* ipc = IPCThreadState::self();
4525 const int pid = ipc->getCallingPid();
4526 const int uid = ipc->getCallingUid();
4527 if ((uid != AID_GRAPHICS) &&
4528 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4529 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4530 return PERMISSION_DENIED;
4531 }
4532 break;
4533 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004534 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004535 return OK;
4536}
4537
4538status_t SurfaceFlinger::onTransact(
4539 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4540{
4541 status_t credentialCheck = CheckTransactCodeCredentials(code);
4542 if (credentialCheck != OK) {
4543 return credentialCheck;
4544 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004545
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004546 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4547 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004548 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004549 IPCThreadState* ipc = IPCThreadState::self();
4550 const int uid = ipc->getCallingUid();
4551 if (CC_UNLIKELY(uid != AID_SYSTEM
4552 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004553 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004554 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004555 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004556 return PERMISSION_DENIED;
4557 }
4558 int n;
4559 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004560 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004561 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004562 return NO_ERROR;
4563 case 1002: // SHOW_UPDATES
4564 n = data.readInt32();
4565 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004566 invalidateHwcGeometry();
4567 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004568 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004569 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004570 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004571 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004572 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004573 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004574 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004575 setTransactionFlags(
4576 eTransactionNeeded|
4577 eDisplayTransactionNeeded|
4578 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004579 return NO_ERROR;
4580 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004581 case 1006:{ // send empty update
4582 signalRefresh();
4583 return NO_ERROR;
4584 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004585 case 1008: // toggle use of hw composer
4586 n = data.readInt32();
4587 mDebugDisableHWC = n ? 1 : 0;
4588 invalidateHwcGeometry();
4589 repaintEverything();
4590 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004591 case 1009: // toggle use of transform hint
4592 n = data.readInt32();
4593 mDebugDisableTransformHint = n ? 1 : 0;
4594 invalidateHwcGeometry();
4595 repaintEverything();
4596 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004597 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004598 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004599 reply->writeInt32(0);
4600 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004601 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004602 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004603 return NO_ERROR;
4604 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004605 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004606 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004607 return NO_ERROR;
4608 }
4609 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004610 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004611 // daltonize
4612 n = data.readInt32();
4613 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004614 case 1:
4615 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4616 break;
4617 case 2:
4618 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4619 break;
4620 case 3:
4621 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4622 break;
4623 default:
4624 mDaltonizer.setType(ColorBlindnessType::None);
4625 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004626 }
4627 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004628 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004629 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004630 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004631 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004632
4633 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004634 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004635 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004636 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004637 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004638 // apply a color matrix
4639 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004640 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004641 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004642 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004643 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004644 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004645 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004646 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004647 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004648 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004649 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004650
4651 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4652 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004653 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004654 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4655 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4656 }
4657
Chia-I Wu28f320b2018-05-03 11:02:56 -07004658 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004659 return NO_ERROR;
4660 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004661 // This is an experimental interface
4662 // Needs to be shifted to proper binder interface when we productize
4663 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004664 n = data.readInt32();
4665 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004666 return NO_ERROR;
4667 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004668 case 1017: {
4669 n = data.readInt32();
4670 mForceFullDamage = static_cast<bool>(n);
4671 return NO_ERROR;
4672 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004673 case 1018: { // Modify Choreographer's phase offset
4674 n = data.readInt32();
4675 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4676 return NO_ERROR;
4677 }
4678 case 1019: { // Modify SurfaceFlinger's phase offset
4679 n = data.readInt32();
4680 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4681 return NO_ERROR;
4682 }
Irvel468051e2016-06-13 16:44:44 -07004683 case 1020: { // Layer updates interceptor
4684 n = data.readInt32();
4685 if (n) {
4686 ALOGV("Interceptor enabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004687 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004688 }
4689 else{
4690 ALOGV("Interceptor disabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004691 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004692 }
4693 return NO_ERROR;
4694 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004695 case 1021: { // Disable HWC virtual displays
4696 n = data.readInt32();
4697 mUseHwcVirtualDisplays = !n;
4698 return NO_ERROR;
4699 }
Romain Guy0147a172017-06-01 13:53:56 -07004700 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004701 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004702 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004703
Chia-I Wu28f320b2018-05-03 11:02:56 -07004704 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004705 return NO_ERROR;
4706 }
Romain Guy54f154a2017-10-24 21:40:32 +01004707 case 1023: { // Set native mode
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004708 int32_t value = data.readInt32();
4709 if (value > 2) {
4710 return BAD_VALUE;
4711 }
4712 if (value == 2 && !mBuiltinDisplaySupportsEnhance) {
4713 return BAD_VALUE;
4714 }
Romain Guy54f154a2017-10-24 21:40:32 +01004715
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004716 mDisplayColorSetting = toDisplayColorSetting(value);
Romain Guy54f154a2017-10-24 21:40:32 +01004717 invalidateHwcGeometry();
4718 repaintEverything();
4719 return NO_ERROR;
4720 }
4721 case 1024: { // Is wide color gamut rendering/color management supported?
4722 reply->writeBool(hasWideColorDisplay);
4723 return NO_ERROR;
4724 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004725 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004726 n = data.readInt32();
4727 if (n) {
4728 ALOGV("LayerTracing enabled");
4729 mTracing.enable();
4730 doTracing("tracing.enable");
4731 reply->writeInt32(NO_ERROR);
4732 } else {
4733 ALOGV("LayerTracing disabled");
4734 status_t err = mTracing.disable();
4735 reply->writeInt32(err);
4736 }
4737 return NO_ERROR;
4738 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004739 case 1026: { // Get layer tracing status
4740 reply->writeBool(mTracing.isEnabled());
4741 return NO_ERROR;
4742 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004743 // Is a DisplayColorSetting supported?
4744 case 1027: {
4745 int32_t value = data.readInt32();
4746 switch (value) {
4747 case 0:
4748 reply->writeBool(hasWideColorDisplay);
4749 return NO_ERROR;
4750 case 1:
4751 reply->writeBool(true);
4752 return NO_ERROR;
4753 case 2:
4754 reply->writeBool(mBuiltinDisplaySupportsEnhance);
4755 return NO_ERROR;
4756 default:
4757 return BAD_VALUE;
4758 }
4759 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004760 }
4761 }
4762 return err;
4763}
4764
Steven Thomas6d8110b2017-08-31 18:24:21 -07004765void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004766 android_atomic_or(1, &mRepaintEverything);
4767 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004768}
4769
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004770// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4771class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004772public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004773 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4774 ~WindowDisconnector() {
4775 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004776 }
4777
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004778private:
4779 ANativeWindow* mWindow;
4780 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004781};
4782
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004783status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4784 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4785 int32_t minLayerZ, int32_t maxLayerZ,
4786 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004787 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004788 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004789
chaviwa76b2712017-09-20 12:02:26 -07004790 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4791
4792 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004793 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4794
chaviwa76b2712017-09-20 12:02:26 -07004795 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4796
4797 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4798 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004799 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004800}
4801
4802status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004803 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004804 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004805 ATRACE_CALL();
4806
4807 class LayerRenderArea : public RenderArea {
4808 public:
Robert Carr578038f2018-03-09 12:25:24 -08004809 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4810 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004811 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004812 mLayer(layer),
4813 mCrop(crop),
4814 mFlinger(flinger),
4815 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004816 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004817 Rect getBounds() const override {
4818 const Layer::State& layerState(mLayer->getDrawingState());
4819 return Rect(layerState.active.w, layerState.active.h);
4820 }
4821 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4822 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4823 bool isSecure() const override { return false; }
4824 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004825 Rect getSourceCrop() const override {
4826 if (mCrop.isEmpty()) {
4827 return getBounds();
4828 } else {
4829 return mCrop;
4830 }
4831 }
4832 bool getWideColorSupport() const override { return false; }
4833 Dataspace getDataSpace() const override { return Dataspace::UNKNOWN; }
Peiyong Linfb069302018-04-25 14:34:31 -07004834 float getDisplayMaxLuminance() const override {
4835 return DisplayDevice::sDefaultMaxLumiance;
4836 }
Robert Carr578038f2018-03-09 12:25:24 -08004837
4838 class ReparentForDrawing {
4839 public:
4840 const sp<Layer>& oldParent;
4841 const sp<Layer>& newParent;
4842
4843 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4844 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004845 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004846 }
Robert Carr15eae092018-03-23 13:43:53 -07004847 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004848 };
4849
4850 void render(std::function<void()> drawLayers) override {
4851 if (!mChildrenOnly) {
4852 mTransform = mLayer->getTransform().inverse();
4853 drawLayers();
4854 } else {
4855 Rect bounds = getBounds();
4856 screenshotParentLayer =
4857 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4858 bounds.getWidth(), bounds.getHeight(), 0);
4859
4860 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4861 drawLayers();
4862 }
4863 }
chaviwa76b2712017-09-20 12:02:26 -07004864
chaviwa76b2712017-09-20 12:02:26 -07004865 private:
chaviw7206d492017-11-10 16:16:12 -08004866 const sp<Layer> mLayer;
4867 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004868
4869 // In the "childrenOnly" case we reparent the children to a screenshot
4870 // layer which has no properties set and which does not draw.
4871 sp<ContainerLayer> screenshotParentLayer;
4872 Transform mTransform;
4873
4874 SurfaceFlinger* mFlinger;
4875 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004876 };
4877
4878 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4879 auto parent = layerHandle->owner.promote();
4880
chaviw7206d492017-11-10 16:16:12 -08004881 if (parent == nullptr || parent->isPendingRemoval()) {
4882 ALOGE("captureLayers called with a removed parent");
4883 return NAME_NOT_FOUND;
4884 }
4885
Robert Carr578038f2018-03-09 12:25:24 -08004886 const int uid = IPCThreadState::self()->getCallingUid();
4887 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4888 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4889 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4890 return PERMISSION_DENIED;
4891 }
4892
chaviw7206d492017-11-10 16:16:12 -08004893 Rect crop(sourceCrop);
4894 if (sourceCrop.width() <= 0) {
4895 crop.left = 0;
4896 crop.right = parent->getCurrentState().active.w;
4897 }
4898
4899 if (sourceCrop.height() <= 0) {
4900 crop.top = 0;
4901 crop.bottom = parent->getCurrentState().active.h;
4902 }
4903
4904 int32_t reqWidth = crop.width() * frameScale;
4905 int32_t reqHeight = crop.height() * frameScale;
4906
Robert Carr578038f2018-03-09 12:25:24 -08004907 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004908
Robert Carr578038f2018-03-09 12:25:24 -08004909 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004910 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4911 if (!layer->isVisible()) {
4912 return;
Robert Carr578038f2018-03-09 12:25:24 -08004913 } else if (childrenOnly && layer == parent.get()) {
4914 return;
chaviwa76b2712017-09-20 12:02:26 -07004915 }
4916 visitor(layer);
4917 });
4918 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004919 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004920}
4921
4922status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4923 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004924 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004925 bool useIdentityTransform) {
4926 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004927
chaviwa76b2712017-09-20 12:02:26 -07004928 renderArea.updateDimensions();
4929
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004930 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4931 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4932 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4933 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004934
4935 // This mutex protects syncFd and captureResult for communication of the return values from the
4936 // main thread back to this Binder thread
4937 std::mutex captureMutex;
4938 std::condition_variable captureCondition;
4939 std::unique_lock<std::mutex> captureLock(captureMutex);
4940 int syncFd = -1;
4941 std::optional<status_t> captureResult;
4942
Robert Carr03480e22018-01-04 16:02:06 -08004943 const int uid = IPCThreadState::self()->getCallingUid();
4944 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4945
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004946 sp<LambdaMessage> message = new LambdaMessage([&]() {
4947 // If there is a refresh pending, bug out early and tell the binder thread to try again
4948 // after the refresh.
4949 if (mRefreshPending) {
4950 ATRACE_NAME("Skipping screenshot for now");
4951 std::unique_lock<std::mutex> captureLock(captureMutex);
4952 captureResult = std::make_optional<status_t>(EAGAIN);
4953 captureCondition.notify_one();
4954 return;
4955 }
4956
4957 status_t result = NO_ERROR;
4958 int fd = -1;
4959 {
4960 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004961 renderArea.render([&]() {
4962 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4963 useIdentityTransform, forSystem, &fd);
4964 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004965 }
4966
4967 {
4968 std::unique_lock<std::mutex> captureLock(captureMutex);
4969 syncFd = fd;
4970 captureResult = std::make_optional<status_t>(result);
4971 captureCondition.notify_one();
4972 }
4973 });
4974
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004975 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004976 if (result == NO_ERROR) {
4977 captureCondition.wait(captureLock, [&]() { return captureResult; });
4978 while (*captureResult == EAGAIN) {
4979 captureResult.reset();
4980 result = postMessageAsync(message);
4981 if (result != NO_ERROR) {
4982 return result;
4983 }
4984 captureCondition.wait(captureLock, [&]() { return captureResult; });
4985 }
4986 result = *captureResult;
4987 }
4988
4989 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004990 sync_wait(syncFd, -1);
4991 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004992 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004993
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004994 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004995}
4996
chaviwa76b2712017-09-20 12:02:26 -07004997void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4998 TraverseLayersFunction traverseLayers, bool yswap,
4999 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005000 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005001
Lloyd Pique144e1162017-12-20 16:44:52 -08005002 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005003
5004 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005005 const auto raWidth = renderArea.getWidth();
5006 const auto raHeight = renderArea.getHeight();
5007
5008 const auto reqWidth = renderArea.getReqWidth();
5009 const auto reqHeight = renderArea.getReqHeight();
5010 Rect sourceCrop = renderArea.getSourceCrop();
5011
5012 const bool filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5013 static_cast<int32_t>(reqHeight) != raHeight;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005014
Dan Stozac1879002014-05-22 15:59:05 -07005015 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005016 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005017 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005018 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Dan Stozac1879002014-05-22 15:59:05 -07005019 }
5020
5021 // ensure that sourceCrop is inside screen
5022 if (sourceCrop.left < 0) {
5023 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5024 }
chaviwa76b2712017-09-20 12:02:26 -07005025 if (sourceCrop.right > raWidth) {
5026 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005027 }
5028 if (sourceCrop.top < 0) {
5029 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5030 }
chaviwa76b2712017-09-20 12:02:26 -07005031 if (sourceCrop.bottom > raHeight) {
5032 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005033 }
5034
Peiyong Lin34beb7a2018-03-28 11:57:12 -07005035 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005036 if (renderArea.getWideColorSupport()) {
5037 outputDataspace = renderArea.getDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08005038 }
Peiyong Linfb069302018-04-25 14:34:31 -07005039 engine.setOutputDataSpace(outputDataspace);
5040 engine.setDisplayMaxLuminance(renderArea.getDisplayMaxLuminance());
Romain Guy88d37dd2017-05-26 17:57:05 -07005041
Mathias Agopian180f10d2013-04-10 22:55:41 -07005042 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005043 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005044
5045 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005046 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
5047 renderArea.getRotationFlags());
Mathias Agopian3f844832013-08-07 21:24:32 -07005048 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005049
chaviw50da5042018-04-09 13:49:37 -07005050 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005051 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005052 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005053
chaviwa76b2712017-09-20 12:02:26 -07005054 traverseLayers([&](Layer* layer) {
5055 if (filtering) layer->setFiltering(true);
5056 layer->draw(renderArea, useIdentityTransform);
5057 if (filtering) layer->setFiltering(false);
5058 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005059}
5060
chaviwa76b2712017-09-20 12:02:26 -07005061status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5062 TraverseLayersFunction traverseLayers,
5063 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005064 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005065 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005066 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005067 ATRACE_CALL();
5068
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005069 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005070
5071 traverseLayers([&](Layer* layer) {
5072 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5073 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005074
Robert Carr03480e22018-01-04 16:02:06 -08005075 // We allow the system server to take screenshots of secure layers for
5076 // use in situations like the Screen-rotation animation and place
5077 // the impetus on WindowManager to not persist them.
5078 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005079 ALOGW("FB is protected: PERMISSION_DENIED");
5080 return PERMISSION_DENIED;
5081 }
5082
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005083 // this binds the given EGLImage as a framebuffer for the
5084 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005085 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005086 if (bufferBond.getStatus() != NO_ERROR) {
5087 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005088 return INVALID_OPERATION;
5089 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005090
Dan Stozaabcda352017-06-01 14:37:39 -07005091 // this will in fact render into our dequeued buffer
5092 // via an FBO, which means we didn't have to create
5093 // an EGLSurface and therefore we're not
5094 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005095 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005096
Dan Stozaabcda352017-06-01 14:37:39 -07005097 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005098 getRenderEngine().finish();
5099 *outSyncFd = -1;
5100
chaviwa76b2712017-09-20 12:02:26 -07005101 const auto reqWidth = renderArea.getReqWidth();
5102 const auto reqHeight = renderArea.getReqHeight();
5103
Dan Stozaabcda352017-06-01 14:37:39 -07005104 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5105 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005106 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005107 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005108 } else {
5109 base::unique_fd syncFd = getRenderEngine().flush();
5110 if (syncFd < 0) {
5111 getRenderEngine().finish();
5112 }
5113 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005114 }
5115
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005116 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005117}
5118
Mathias Agopiand5556842013-09-19 17:08:37 -07005119void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005120 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005121 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005122 for (size_t y = 0; y < h; y++) {
5123 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5124 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005125 if (p[x] != 0xFF000000) return;
5126 }
5127 }
chaviwa76b2712017-09-20 12:02:26 -07005128 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005129
Robert Carr2047fae2016-11-28 14:09:09 -08005130 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005131 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005132 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005133 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5134 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5135 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5136 static_cast<float>(state.color.a));
5137 i++;
5138 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005139 }
5140}
5141
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005142// ---------------------------------------------------------------------------
5143
Dan Stoza412903f2017-04-27 13:42:17 -07005144void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5145 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005146}
5147
Dan Stoza412903f2017-04-27 13:42:17 -07005148void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5149 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005150}
5151
chaviwa76b2712017-09-20 12:02:26 -07005152void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
5153 int32_t maxLayerZ,
5154 const LayerVector::Visitor& visitor) {
5155 // We loop through the first level of layers without traversing,
5156 // as we need to interpret min/max layer Z in the top level Z space.
5157 for (const auto& layer : mDrawingState.layersSortedByZ) {
5158 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5159 continue;
5160 }
5161 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005162 // relative layers are traversed in Layer::traverseInZOrder
5163 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005164 continue;
5165 }
5166 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005167 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5168 return;
5169 }
chaviwa76b2712017-09-20 12:02:26 -07005170 if (!layer->isVisible()) {
5171 return;
5172 }
5173 visitor(layer);
5174 });
5175 }
5176}
5177
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005178}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005179
5180
5181#if defined(__gl_h_)
5182#error "don't include gl/gl.h in this file"
5183#endif
5184
5185#if defined(__gl2_h_)
5186#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005187#endif